Vue.js 3 에서 Custom Directives 를 사용하는 방법에 대해 포스팅 하겠다.
■ Custom Directive
1. v-model, v-show 디렉티브 같은 기본 디렉티브 이외에도 사용자가 직접 디렉티브를 정의해서 사용할 수 있다.
2. 전역에서 사용할 수 있다. 물론 각각의 컴포넌트에서도 가능하다.
-> 사용하기에 따라 유용하겠죠?
예시) 사용자가 컴포넌트에 접속했을 때,
입력필드로 자동 포커스 ( === autofocus) 되는 커스텀 디렉티브와
배경이 노란색의 컴포넌트
■ 전역 컴포넌트 사용하기
// Directives.js
// 1.배경색 노란색으로 설정
export const MyHighlightDirective = {
beforeMount(el){
el.style.background = 'yellow'
}
}
// 2. mounted 후에 focus로 해당 항목에 자동으로 focus. === html: autofocus
export const MyFocus = {
mounted(el) {
el.focus()
}
}
// main.js
import { MyHighlightDirective, MyFocus } from './directive/HighlightDirective'
// 보기 편하게 directive를 2개로 분리하였다. 배열로 해도 상관없을까?
createApp(App)
.directive('highlight', MyHighlightDirective)
.directive('focus', MyFocus)
.use(router).mount('#app')
main.js에 import 후, 아무 컴포넌트에서 해당 directive를 호출이 가능
-> 전역으로 등록하였기 때문에 별도의 선언·호출 없이 사용이 가능하다.
// Directives.vue
<template>
<div>
<h1>Directives</h1>
<p v-highlight>It will be background yellow by Direction : "v-highlight" by Directions</p>
<input v-focus type="text">
</div>
</template>
■ 컴포넌트 내부에서 선언하고 사용하기
- 오히려 전역으로 등록하는 것보다 간단하다.
// Directives.vue
<template>
<div>
<h1>Directives</h1>
<p v-highlight>It will be background yellow by Direction : "v-highlight" by Directions</p>
<input v-focus type="text"><br>
<p v-backgroundRed>It will be background red</p>
</div>
</template>
<script>
export default {
directives: {
backgroundRed: {
beforeMount(el) {
el.style.background = 'red'
el.style.color = 'white'
}
}
}
}
</script>
이상입니다.
Custom Directives
v-model, v-show 디렉티브 같은 기본 디렉티브 이외에도 사용자가 직접 디렉티브를 정의해서 사용할 수 있다.
sun-bobolink-b3b.notion.site
반응형