1. 程式人生 > 其它 >vue3的自定義指令API

vue3的自定義指令API

vue3中指令api和元件保持一致,具體表現在:

  • bind → beforeMount

  • inserted → mounted

  • beforeUpdate: new! 元素自身更新前呼叫, 和元件生命週期鉤子很像

  • update → removed! 和updated基本相同,因此被移除之,使用updated代替。

  • componentUpdated → updated

  • beforeUnmount new! 和元件生命週期鉤子相似, 元素將要被移除之前呼叫。

  • unbind → unmounted

Vue支援全域性註冊和區域性註冊指令。
全域性註冊註冊通過app例項的directive方法進行註冊。

import { createApp } from 'vue'
import App from './App.vue'
import './index.css'


let app = createApp(App)
app.directive('highlight', {
    beforeMount(el, binding, vnode) {
    el.style.background = binding.value
    }
}).mount('#app')
<p v-highlight="'yellow'">Highlight this text bright yellow<
/p>

在這裡插入圖片描述

區域性註冊通過給元件設定directive屬性註冊

export default defineComponent({

name: "WebDesigner",

components: {

Designer,

},

directives: {

highlight: {

beforeMount(el, binding, vnode) {

el.style.background = binding.value;

},

},

},

});