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;
},
},
},
});