1. 自定义指令
- 在main.js中定义自定义指令
//main.js
//省略其代码
const app = createApp(App)
app.directive('focus', {
mounted (el, binding) {
console.log(el, binding, '聚焦', el.nodeName);
}
})
2.使用指令
<input v-focus="'yyds'" />
3.浏览器打印输出自定义指令钩子函数的两个参数
可以看到:
el是指令绑定到的dom元素,这里我们绑定了input
binding.value是: 我们绑定的值是yyds,
注意
上面字符串的绑定方法
传参方式:
我们可以像v-text=”’test’”一样,把我们需要传递的值放在‘=’号后面传递过去。
我们可以像v-on:click=”handClick” 一样,为指令传递参数’click’。
我们可以像v-on:click.stop=”handClick” 一样,为指令添加一个修饰符。
我们也可以像v-once一样,什么都不传递。
vue3 钩子函数:
created:在绑定元素的 attribute 或事件监听器被应用之前调用。在指令需要附加须要在普通的 v-on 事件监听器前调用的事件监听器时,这很有用。
beforeMount:当指令第一次绑定到元素并且在挂载父组件之前调用。
mounted:在绑定元素的父组件被挂载后调用。
beforeUpdate:在更新包含组件的 VNode 之前调用。
updated:在包含组件的 VNode 及其子组件的 VNode 更新后调用。
beforeUnmount:在卸载绑定元素的父组件之前调用
unmounted:当指令与元素解除绑定且父组件已卸载时,只调用一次。
vue2的钩子函数:
bind、inserted、update、componentUpdate和unbind。
4.简单封装到 directives/index.js
// src/directives/index.js
const focusDirective = {
install (app) {
// 自定义指令
app.directive('focus', {
mounted (el, binding) {
console.log(el, binding, '聚焦', el.nodeName);
}
})
}
}
export default focusDirective
在main.js中引入,并使用
// 省略其他
// 引入全局指令
import focusDirective from '@/directives'
const app = createApp(App)
app.use(store).use(router).use(myPlugin).use(focusDirective ).mount('#app')