我正在参与掘金创作者训练营第5期,点击了解活动详情
前言
本文主要介绍了Vue 自定义指令directived的使用,包括局部自定义指令、全局自定义指令、自定义指令动态参数、 传参给自定义指令等用法。
自定义指令directive
在Vue中除了像v-model 和 v-show这样的默认内置的指令外, Vue 也允许注册自定义指令。自定义指令用于对DOM 元素进行操作。
局部自定义指令
局部自定义指令类似局部组件,组件使用directives进行引用,以输入框自动获得焦点为例。
注册一个局部自定义指令 v-focus,并写入钩子mounted,mounted接收绑定元素el。
const directives = {
focus:{
mounted(el){
el.focus();
}
}
}
组件引用局部自定义指令,并使用自定义指令 v-focus
const app = Vue.createApp({
directives: directives,
template:`<input v-focus/>`
});
页面效果:
全局自定义指令
全局自定义指令类似全局组件全局可用,还以输入框自动获得焦点为例。
首先注册一个全局自定义指令 v-focus,并写入钩子mounted,mounted接收绑定元素el。
app.directive('focus', {
mounted(el){
el.focus();
}
})
使用自定义指令 v-focus。
<input v-focus/>
页面效果:
自定义指令动态参数
沿用上述代码并进行相关调整。
将自定义指令名修改为top,增加一个钩子 update,并且两个钩子都使用binding接收动态参数。
app.directive('top', {
// 第一次渲染
mounted(el, binding){
el.style.top = `${binding.value}px`;
},
// 更新后重新渲染
update(el, binding){
el.style.top = `${binding.value}px`;
}
})
用div将input包裹起来,在div上使用自定义指令,并加上绝对定位。
const app = Vue.createApp({
data(){
return{
top: 50
}
},
template:`
<div v-top="top" class="pos">
<input />
</div>
`
});
页面效果:
函数简写
在前面的例子中, mounted 和 updated 时触发相同行为。那么就可以通过回调函数传递给指令来简写。
app.directive('top', (el, binding) => {
el.style.top = `${binding.value}px`;
})
传参给自定义指令
arg:参数传递给指令。例如在 v-top:left 中,arg 为 "left"。
结合arg,进行完善代码。
<div v-top:left="distance" class="pos">
<input />
</div>
页面效果:
总结
使用定义directive自定义指令;
局部自定义指令,组件使用directives进行引用;
全局自定义指令类似全局组件全局可用;
mounted 和 updated 时触发相同行为。可以通过回调函数简写;
arg参数传递给指令。v-top:left;
结语
本文到此结束
如果大家还有什么其他想法,欢迎在评论区交流!