自定義指令
自定義指令分為兩種:
- 自定義局部指令:組件通過directives選項們只能在當前組件中使用
- 自定義全局指令:app的directive方法,可以在任意組件中使用
案例:當input元素掛載完成之后可以自動獲取焦點
實現方式一:使用默認的實現方式
<template> <div> <input type="text" ref="input"> </div> </template> <script> import {ref,onMounted} from "vue" export default { setup(){ const input=ref(null) onMounted(()=>{ input.value.focus() }) return { input } } } </script>
頁面加載之后自動獲取焦點
實現方式二:自定義一個v-focus的局部指令
<template> <div> <input type="text" v-focus> </div> </template> <script> export default { directives:{ focus:{ // 當這個掛載完成之后執行mounted,接收四個參數 mounted(el,bindings,vnode,preVnode) { console.log(el) console.log(bindings) console.log(vnode) console.log(preVnode) }, } }, } </script>
所以拿到el之后直接el.focus即可自動獲取焦點
mounted(el,bindings,vnode,preVnode) {
el.focus()
},
指令是可以添加修飾符還有參數的,這些部分可以在第二次參數中binding中可以看到
<template> <div> <input type="text" v-focus.abc="'xyz'"> </div> </template> <script> export default { directives:{ focus:{ // 當這個掛載完成之后執行mounted,接收四個參數 mounted(el,bindings,vnode,preVnode) { console.log(bindings) }, } }, } </script>
console.log(bindings.value)
console.log(bindings.modifiers)
實現方式三:自定義一個v-focus的全局指令
import { createApp } from 'vue' import App from './2/App.vue' const app=createApp(App) // 傳入兩個參數,第一個是指定的名稱,第二個是一個對象 app.directive('focus',{ mounted(el,bindings,vnode,preVnode) { el.focus() }, }) app.mount('#app')
指令的生命周期
一個指令定義的對象,Vue提供了一下幾個鈎子:
created:在綁定元素的attribute或事件監聽器被應用之前調用;
beforeMount:當指令第一次綁定到元素並掛載父組件之前調用;
mounted:在綁定元素的父組件被掛載后調用;
beforeUpdate:在更新包含組件的VNode之前調用;
updated:在包含組件的VNode及其子組件的VNode更新后調用;
beforeUnmount:在卸載綁定元素的父組件之前調用;
unmounted:當指令與元素解除綁定且父組件已卸載時,只調用一次;
<template> <div> <h2 >當前計數:{{ counter }}</h2> <button v-if="counter<2" v-my @click="add">+</button> </div> </template> <script> import { ref } from "vue"; export default { directives: { my: { created() { console.log("created"); }, beforeMount() { console.log("beforeMount"); }, mounted() { console.log("mounted"); }, beforeUpdate() { console.log("beforeUpdate"); }, updated() { console.log("updated"); }, beforeUnmount() { console.log("beforeUnmount"); }, unmounted() { console.log("unmounted"); }, }, }, setup() { const counter = ref(0); const add = () => counter.value++; return { counter, add, }; }, }; </script>
點擊加一之后
再次點擊之后