vue2和vue3的自定义指令
1.什么是自定义指令?
想要使用自定义指令,首先我们得搞清楚什么是自定义指令?
自定义指令非常好理解,我们使用的v-for、v-if、v-model等等称之为指令,也被称之为Vue的内置指令。这些指令都是我们可以直接使用的。
为了更好的满足需求,最大化的让开发者个性化开发,Vue暴漏了自定义指令的API给我们,让我们除了使用内置指令外,我们还可以自己定义指令,定义好后和内置指令的方式非常类似。
2、自定义指令分类
局部自定义指令:只在组件内有效
全局自定义指令:所有组件都有效
3、Vue2的自定义指令
这就用到了V2的自定义指令钩子函数:
bind:只会调用一次,指令 第一次 绑定到元素时会调用;inserted:被绑定元素插入父节点时调用 。还有update,componentUpdated,unbind
局部自定义指令
在组件中,用自定义指令实现改变文字颜色
<p v-style>哈哈哈哈哈哈</p>
directives: {
style: {
bind(el,binding) {
el.style.fontSize = "30px";
el.style.color = "blue";
},
update(el,binding){
el.style.fontSize = "30px";
el.style.color = "blue";
}
},
},
style:指令的名称,使用的时候要加前面加个v-
bind:只会调用一次指令 第一次 绑定到元素时会调用
el:是指绑定的这个dom元素本身
binding:获取绑定指令的信息(name:指令名称;rawName:指令全称:value:指定绑定的值)
update:元素第一次绑定不会触发,绑定的值发生更新触发,参数与binding是相同的,如果逻辑与bind相同的话可以直接把指令当成函数写,上面的指令是对象类型。
v-style:使用指令改变了元素的样式
全局自定义指令
使用Vue.directive(‘指令名称’,{钩子函数})
directives: {
style(){
el.style.fontSize = "30px";
el.style.color = "blue";
},
},
4.Vue3自定义指令
指令钩子函数有7个:created,beforeMount,mounted,beforeUpdate,updated,beforeUnmount,unmounted
局部注册两种方式
<script lang="ts" setup>
// 局部指令, 变量名为驼峰命名(vMsg = v-msg)
const vMsg= {
mounted: (el:any) => {
el.msg()
console.log(el, '获得焦点')
}
}
</script>
<script lang="ts">
const vMsg = {
focus: {
mounted(el:any){
el.msg();
console.log(el, "获得焦点");
}
},
};
export default {
setup() { },
directives: vMsg ,
};
</script>
全局注册
<input type="text" v-focus>
在directives文件夹新建msg.ts文件
const directives: any = {
mounted(el: any) {
el.msg();
el.value = '1'
}
}
export default {
name: "msg",
directives
}
在directives文件夹新建index.js
import type { App } from 'vue'
import msg from './msg'
export default function installDirective(app: App) {
app.directive(msg.name, msg.directives);
}
main.ts文件
import directives from './directives'
const app = createApp(App);
app.use(directives);