17. 기존 event handler 실행 전에 어떤 로직을 추가해야된다면..
기존 서비스에서 클릭했을 때, 어떤 동작을 실행시키는 컴포넌트들이 있다면..
그런데 그 컴포넌트들이 각 페이지에 많다면..
그 컴포넌트들을 클릭했을 때 어떤 사전 작업이 되어야 한다면?
각 메서드마다 그 사전작업을 추가하기가 어렵고, 애매하다면..
다음과 같은 방법을 사용할 수 있다.
<template>
<custom-button @click="onClick">버튼</custom-button>
</template>
<script>
export default {
setup() {
const onClick = () => {
// 어떤 동작 실행..
}
return {
onClick,
}
}
}
</script>
- 기존 컴포넌트를 감싸는 컴포넌트 생성 및 감싸기
<template>
<div>
<slot></slot>
</div>
</template>
<script>
export default {
setup(props, { slots }) {
// slots.default?.()[0]
// 위 코드 활용
// slot 에 랜더링되는 VNode에 접근 후 click 이벤트에 먼저 실행되어야하는 로직 추가
// 사전에 실행되어야하는 로직을 실행 후
// 원래 실행되어야하는 로직을 실행하면 된다.
}
}
</script>
<template>
<custom-prefer-logic>
<custom-button @click="onClick">버튼</custom-button>
</custom-prefer-logic>
</template>
<script>
export default {
setup() {
const onClick = () => {
// 어떤 동작 실행..
}
return {
onClick,
}
}
}
</script>