一,自定义指令的vue3和vue2的写法变化
官网中是这样介绍的:https://v3.cn.vuejs.org/guide/migration/custom-directives.html#_2-x-%E8%AF%AD%E6%B3%95
在 Vue 3 中,我们为自定义指令创建了一个更具凝聚力的 API。正如你所看到的,它们与我们的组件生命周期方法有很大的不同,即使钩子的目标事件十分相似。我们现在把它们统一起来了:
created - 新增!在元素的 attribute 或事件监听器被应用之前调用。
bind → beforeMount
inserted → mounted
beforeUpdate:新增!在元素本身被更新之前调用,与组件的生命周期钩子十分相似。
update → 移除!该钩子与 updated 有太多相似之处,因此它是多余的。请改用 updated。
componentUpdated → updated
beforeUnmount:新增!与组件的生命周期钩子类似,它将在元素被卸载之前调用。
unbind -> unmounted
因为vue3中,app的产生是const app = Vue.createApp({}),所以vue3中需要app.directive来注册自定义指令。
const app = Vue.createApp({})
app.directive('highlight', {
beforeMount(el, binding, vnode) {
el.style.background = binding.value
}
})
使用时:
<p v-highlight="'yellow'">以亮黄色高亮显示此文本</p>
二,我在项目中的使用示例
有的按钮在点击的时候,会发送请求。用户有时会快速重复点击。为了避免重复发送请求,需要让用户一段时间内只能发送一次请求。于是就可以自定义指令,让按钮节流:
新建useDirective.js文件:
export const direct = app => {
app.directive('clickOnce', {
mounted(el, binding, vnode) {
el.addEventListener('click', () => {
if (!el.disabled) {
el.disabled = true;
setTimeout(() => {
el.disabled = false;
}, binding.value || 1000);
}
});
}
});
};
然后在入口文件中引入注册:
import { direct } from '@/vue-use/useDirective.js';
const app = createApp(App);
direct(app);
在页面代码中的使用:
<button class="login-page-handle" @click="handleLogin()" v-clickOnce>
登 录
</button>