全局注册
在 src 文件夹下,创建一个 directives 文件夹,存放自定义指令的js文件
在 directives 文件夹中,创建一个 index.js 文件,用于导出自定义指令
创建 checkSysStatus.js 在文件中写自定义指令的功能
在这个 index.js 文件中
import checkSysStatus from './checkSysStatus'; // 引入自定义指令的js文件
// 导出自定义指令
const directives = {
checkSysStatus
}
export default {
install(app) {
Object.keys(directives).forEach(key => {
app.directive(key, directives[key]);
});
}
}
在main.js文件中,导入并使用自定义指令
import directives from "@/directives/index.js";
app.use(directives);
功能要求
点击后要发送请求,根据接口返回的值判断该链接能否点击,并提示用户
实现
import getSomething from "@/api/sys/getSomething"; // 这个是引入接口,或者其他东西
import { ElMessage } from "element-plus"; // 这个是引入element-plus的消息提示组件
// 应用于a标签,通过监测 getSomething 请求传回的 somthing 字段 ,来判断是否可以进行跳转
const checkSysStatus = {
mounted(el, binding){
let timer;
el.handler = (e)=>{
// 阻止a标签的默认跳转事件
e.preventDefault();
// 0.3秒触发一次这个点击事件,防抖
if (timer) {
clearTimeout(timer);
};
timer = setTimeout(()=>{
getConfig.getConfig().then(res=>{
if (res.systemStatus==1) {
// 打开新窗口,跳转到对应的链接
window.open(el.href);
}else{
ElMessage.warning("系统维护中,请稍后再试");
}
})
},300);
}
// 监听a标签的点击事件
el.addEventListener('click', el.handler);
},
unmounted(el) {
el.removeEventListener("click", el.handler);
},
};
// 以这个名字导出
export default checkSysStatus;
使用时
在a标签上使用
<a v-checkSysStatus href="www.baidu.com" target="_blank">百度</a>