Vue3自定义指令
1、先写一个自定义指令的文件
// 背景颜色自定义指令
export function DivColor(app) {
app.directive('highlight', {
mounted(el, binding) {
console.log('el', el);
console.log('binding111', binding);
el.style.backgroundColor = "#36d"
},
})
}
// 防抖的自定义组件
export function btnDeClick(app) {
app.directive('debounce', {
mounted(el, binding) {
console.log('el', el);
console.log('binding222', binding);
let debounceTime = binding.value || 2000; // 默认防抖时间 2秒,或者传入自定义时间
let timer;
const handleClick = (e) => {
// 如果按钮被禁用,防止继续执行事件
if (el.disabled) return;
// 执行按钮点击事件
el.disabled = true; // 禁用按钮
// 设置定时器,防止在指定时间内再次点击
timer = setTimeout(() => {
el.disabled = false; // 恢复按钮状态
}, debounceTime);
};
el.addEventListener('click', handleClick);
},
})
}
2、在main.js里注册全局指令
import { createApp } from 'vue'
import router from './router/index.js'
import store from "./store/index.js"
import App from './App.vue'
import {DivColor,btnDeClick} from './plugIn/vHiglight.js'
const app = createApp(App)
//注册指令
DivColor(app)
btnDeClick(app)
app.use(VXETable)
app.use(print)
app.use(router)
app.use(store)
app.mount("#app")
3、使用指令
<template>
<div>
<span v-highlight style="font-weight: 900; font-size: 12px; color: #000">这个div的背景颜色被改变了</span>
<el-button v-debounce="5000" @click="searchData" >这个按钮每隔5秒才能执行</el-button>
</div>
</template>
原文地址:https://blog.csdn.net/sisuiban/article/details/143901453
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!