自定义指令
vue官方提供了v-text、v-for、v-model、v-if等常用的指令,还允许开发者自定义指令。
在使用自定义指令前,须在自定义名称前加v-名称
私有自定义指令
<template>
<div>
<div v-color="num" @click="updateNum">我被改变颜色---{{ num }}</div>
<input v-focus type="text" />
<div v-changeGreen>全局自定义指令---变成绿色</div>
</div>
</template>
<script>
import { ref } from "@vue/reactivity";
export default {
setup () {
const num = ref(0);
const updateNum = () => {
num.value++
}
return {
num,
updateNum
}
},
// 私有自定义指令
directives: {
// 分步骤
color: {
// 当指令第一次被绑定到元素上的时候,会立即触发 mounted(vue3),bind(vue2) 函数,只触发一次
// vue3写法
mounted (el, bind) {
el.style.color = 'red';
console.log('变成红色', bind.value);
},
// vue2写法
bind (el, bind) {
el.style.color = 'red';
console.log('变成红色', bind.value);
},
// 当dom更新时,会触发updated(vue3),update(vue2)函数
// vue3写法
updated (el, bind) {
console.log('dom更新了', bind.value);
}
// vue2写法
update(el, bind) {
console.log('dom更新了', bind.value);
}
},
// 函数式写法
color (el, bind) {
el.style.color = 'red';
console.log('变成红色', bind.value);
console.log('dom更新了', bind.value);
},
// 输入框自动聚焦
focus: {
// vue3写法
mounted (el) {
el.focus();
},
// vue2有inserted函数
inserted (el) {
el.focus();
}
}
}
};
</script>
全局自定义指令
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
const app = createApp(App)
// 全局自定义指令
app.directive('changeGreen', {
mounted (el) {
el.style.color = 'green'
console.log('全局指令变成绿色');
}
})
app.use(store).use(router).mount('#app')