[ Vue.js ] How to use Custom Directives in Vue.js 3?? | vue.js3에서 커스텀 디렉티브 사용하는 방법 예제
// 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')
// 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>
이상입니다.
댓글 영역