企业营销网站建设站长资讯
除了 Vue 内置的一系列指令 (比如 v-model 或 v-show) 之外,Vue 还允许你注册自定义的指令 (Custom Directives)
选项式API_自定义指令
<template><h3>自定义指令</h3><p v-author>文本信息</p>
</template>
<script>
export default {directives:{author:{mounted(element){element.innerHTML = element.innerHTML + "-itbaizhan"}}}
}
</script>
组合式API_自定义指令
<template><h3>自定义指令</h3><p v-author>文本信息</p>
</template>
<script setup>
const vAuthor = {mounted:(element) =>{element.innerHTML = element.innerHTML + "-itbaizhan"}
}
</script>
全局与局部自定义指令
自定义指令是区分全局和局部注册,在全局注册,可以在任意组件中使用,局部注册,只在当前组件中使用
局部自定义指令
<template><h3>自定义指令</h3><p v-blue>蓝色效果</p>
</template>
<script>
export default {directives:{blue:{mounted(element){element.style.color = "blue"}}}
}
</script>
全局自定义指令
import { createApp } from 'vue'
import App from './App.vue'const app = createApp(App)app.directive("red",{mounted(element){element.style.color = 'red'}
})app.mount('#app')
自定义指令钩子函数
自定义指令有很多钩子函数,我们可以理解为是自定义指令的生命周期函数,在不同的情况下会自动调用
钩子函数
<template><h3>自定义指令</h3><p v-red v-if="flag">{{ message }}</p><button @click="updateHandler">修改数据</button><button @click="delHandler">删除元素</button>
</template>
<script setup>
import { ref } from "vue"
const message = ref("红色效果")
const flag = ref(true)
function updateHandler(){message.value = "修改的红色效果"
}
function delHandler(){flag.value = false
}
const vRed = {// 在绑定元素的 attribute 前// 或事件监听器应用前调用created(el, binding, vnode, prevVnode) {console.log("created");},// 在元素被插入到 DOM 前调用beforeMount(el, binding, vnode, prevVnode) {console.log("beforeMount");},// 在绑定元素的父组件// 及他自己的所有子节点都挂载完成后调用mounted(el, binding, vnode, prevVnode) {console.log("mounted");},// 绑定元素的父组件更新前调用beforeUpdate(el, binding, vnode, prevVnode) {console.log("beforeUpdate");},// 在绑定元素的父组件// 及他自己的所有子节点都更新后调用updated(el, binding, vnode, prevVnode) {console.log("updated");},// 绑定元素的父组件卸载前调用beforeUnmount(el, binding, vnode, prevVnode) {console.log("beforeUnmount");},// 绑定元素的父组件卸载后调用unmounted(el, binding, vnode, prevVnode) {console.log("unmounted");}
}
</script>
自定义指令钩子函数参数
指令的钩子会传递以下几种参数
el:指令绑定到的元素。这可以用于直接操作 DOM。
binding:一个对象,包含以下属性。
value:传递给指令的值。例如在 v-my-directive=“1 + 1” 中,值是 2。
oldValue:之前的值,仅在 beforeUpdate 和 updated 中可用。无论值是否更改,它都可用。
arg:传递给指令的参数 (如果有的话)。例如在 v-my-directive:foo 中,参数是 “foo”。
modifiers:一个包含修饰符的对象 (如果有的话)。例如在 v-my-directive.foo.bar 中,修饰符对象是 { foo: true, bar: true }。
instance:使用该指令的组件实例。
dir:指令的定义对象。
vnode:代表绑定元素的底层 VNode。
prevNode:之前的渲染中代表指令所绑定元素的 VNode。仅在 beforeUpdate 和 updated 钩子中可用。
模拟v-show指令
<template><h3>自定义指令</h3><p v-myShow="flag">{{ message }}</p><button @click="updateHandler">显隐Toggle</button>
</template>
<script setup>
import { ref } from "vue"
const message = ref("模拟v-show指令")
const flag = ref(true)
function updateHandler(){flag.value = flag.value === true ? flag.value=false : flag.value = true
}
const vMyShow = {updated(el, binding) {binding.value === true ? el.style.display='block' : el.style.display='none'}
}
</script>