1.自定义指令
自定义指令就是类似于v-on v-bind那样的指令,只不过是自己定义的
2.局部自定义指令
const app = Vue.createApp({
//局部指令需要注册后才能使用
directives
template: `
<div>
<input v-focus/>
</div>
`,
});
// 局部指令
const directives = {
focus: {
// 组件挂载时让它focus
mounted(el) {
el.foucs();
},
},
};
3.全局自定义指令
const app = Vue.createApp({
template: `
<div>
<input v-focus/>
</div>
`,
});
// 全局指令
app.directive("focus", {
beforeMount() {
console.log("beforeMount");
},
beforeUpdate() {},
updated() {},
mounted(el) {
el.focus();
},
beforeUnmount() {},
unmounted() {},
});
4.自定义指令传参
<style>
.header {
position: absolute;
}
</style>
const app = Vue.createApp({
data:{
return {
left: 200
}
},
template: `
<div >
//通过=指定参数,:后面指定的是参数名
<div v-pos:left="left" class="header">
<input/>
</div>
</div>
`,
});
app.directive("pos", {
// 通过binding传过来参数
mounted(el, binding) {
el.style.top = binding.value + "px";
},
// 数据改变时也会执行
updated(el, binding) {
el.style.top = binding.value + "px";
},
});
//也可以简写为下面的形式
app.directive("pos", (el, binding) => {
el.style[binding.arg] = binding.value + "px";
});