VUE不僅為我們提供了自定義組件,還提供了自定義指令。當然,這個玩意我在VUE2中是沒有用到過的。
VUE3中我大概試一下這個自定義指令:
官方文檔:
https://vue3js.cn/docs/zh/guide/custom-directive.html#動態指令參數
一:注冊全局指令
在main.ts中加入如下配置:
// =======================================================
// 注冊一個全局自定義指令 `v-focus`
app.directive('console', {
// 當被綁定的元素插入到 DOM 中時……
mounted(el) {
// Focus the element
// el.focus()
console.log('自定義全局指令v-console 注冊成功');
}
})
二:注冊局部指令
在某個頁面的js中:
name: "index",
components: {},
/**
* @name: 自定義指令(局部注冊)
* @author: camellia
* @email: guanchao_gc@qq.com
* @date: 2021-02-25
*/
directives: {
// v-part
part: {
// 指令的定義
mounted(el: any) {
// el.focus()
console.log(el);
console.log('自定義局部指令注冊成功!');
}
}
},
三:v-preventReClick,防止多次點擊,重復請求
name: "index",
components: { },
/**
* @name: 自定義指令(局部注冊)
* @author: camellia
* @email: guanchao_gc@qq.com
* @date: 2021-02-25
*/
directives: {
// v-part
preventReClick: {
// 指令的定義
mounted(el: any, binding:any) {
// el.focus()
console.log(el);
console.log(binding);
// console.log('自定義局部指令注冊成功!');
el.addEventListener('click', () => {
if (!el.disabled) {
console.log(123);
el.disabled = true;
setTimeout(() => {
el.disabled = false;
}, binding.value || 300);
}
});
}
}
},
四:調用方式
<button @click="handle" v-preventReClick>提交</button>
以上大概就是VUE3中自定義指令的大概使用。
有好的建議,請在下方輸入你的評論。
歡迎訪問個人博客
https://guanchao.site