自定义指令分为全局和局部两种类型,大家并不陌生。今天我们就讲讲在 vue3 中,自定义指令定义、使用以及钩子函数都有哪些变化?
以下实例都是实现一个输入框自动获取焦点的自定义指令。
1.1、全局自定义指令
在vue2中,全局自定义指令通过 directive 挂载到 Vue 对象上,使用 Vue.directive('name',opt)。
实例1:Vue2 全局自定义指令
Vue.directive('focus',{
inserted:(el)=>{
el.focus()
}
})
inserted 是钩子函数,在绑定元素插入父节点时执行。
在 vue3 中,vue 实例通过createApp 创建,所以全局自定义指令的挂载方式也改变了, directive 被挂载到 app上。
实例2:Vue3 全局自定义指令
//全局自定义指令
app.directive('focus',{
mounted(el){
el.focus()
}
})
//组件使用
<input type="text" v-focus />
在组件内部,使用 directives 引入的叫做局部自定义指令。Vue2 和 Vue3 的自定义指令引入是一模一样的。
实例3:局部自定义指令
<script>
//局部自定义指令
const defineDir = {
focus:{
mounted(el){
el.focus()
}
}
}
export default {
directives:defineDir,
setup(){}
}
</script>
一个指令定义对象可以提供如下几个钩子函数(都是可选的,根据需要引入)
实例3:测试指令内生命周期函数执行
<template>
<div>
<input type="text" v-focus v-if="show"><br>
<button @click="changStatus">{{show?'隐藏':'显示'}}</button>
</div>
</template>
//局部自定义指令
const autoFocus = {
focus:{
created(){
console.log('created');
},
beforeMount(){
console.log('beforeMount');
},
mounted(el){
console.log('mounted');
},
beforeUpdated(){
console.log('beforeUpdated')
},
updated(){
console.log('updated');
},
beforeUnmount(){
console.log('beforeUnmount');
},
unmounted(){
console.log('unmounted');
}
},
}
import { ref } from 'vue'
export default {
directives:autoFocus,
setup(){
const show = ref(true)
return {
show,
changStatus(){
show.value = !show.value
}
}
}
}
通过点击按钮,我们发现创建 input 元素的时候,会触发 created、beforeMount 和 mounted 三个钩子函数。
隐藏 input 元素的时候,会触发 beforeUnmount 和 unmounted 。
然而我们添加的 beforeUpdate 和 updated 函数并没有执行。
此时我们把 input 元素上的 v-if 修改成 v-show 就会执行上述两个方法了,具体的执行情况自行验证下。
从 vue2 升级到 vue3 ,自定义指令的生命周期钩子函数发生了改变,具体变化如下:
钩子函数被赋予了以下参数:
binding 包含的属性具体的分别为:
<template>
<div>
<div v-fixed >定位</div>
</div>
</template>
<script>
//自定义指令动态参数
const autoFocus = {
fixed:{
beforeMount(el,binding){
console.log('el',el)
console.log('binding',binding)
}
}
}
export default {
directives:autoFocus,
setup(){
}
}
</script>
自定义指令的也可以带参数,参数可以是动态的,参数可以根据组件实例数据进行实时更新。
实例4:自定义指令动态参数
<template>
<div>
<div v-fixed:pos="posData" style="width:100px;height:100px;background:grey">定位</div>
</div>
</template>
<script>
//自定义指令动态参数
const autoFocus = {
fixed:{
beforeMount(el,binding){
el.style.position = "fixed"
el.style.left = binding.value.left+'px'
el.style.top = binding.value.top + 'px'
}
}
}
export default {
directives:autoFocus,
setup(){
const posData = {
left:20,
top:200
}
return {
posData,
}
}
}
</script>
什么时候需要自定义指令?
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://www.cnblogs.com/web-learn/p/15565626.html
内容来源于网络,如有侵权,请联系作者删除!