**********远程指令**********
// repeat-click/index.js
export default {
beforeMount: (el, binding) => {
let throttleTime = binding.value; // 防抖时间
if (!throttleTime) {
// 用户若不设置防抖时间,则默认1.5s
throttleTime = 1500;
}
let timer;
let disable = false;
el.__useCapture = el.tagName !== 'BUTTON'; // 兼容相对低版本浏览器
el.__throttleEvent = event => {
if (timer) {
clearTimeout(timer);
}
if (!disable) {
// 第一次执行(一点击触发当前事件)
disable = true;
el.setAttribute('disabled', true);
} else {
event && event.stopImmediatePropagation();
}
timer = setTimeout(() => {
timer = null;
disable = false;
el.removeAttribute('disabled');
}, throttleTime);
};
el.addEventListener('click', el.__throttleEvent, el.__useCapture);
},
unmounted: (el) => {
el.removeEventListener('click', el.__throttleEvent, el.__useCapture);
},
};
// index.js
import repeatClick from './repeat-click'
const directives = {
repeatClick
}
export default {
install (app) {
return Object.keys(directives).forEach((key) => {
app.directive(key, directives[key])
})
}
}
// package.json
{
"name": "remote-directives",
"version": "0.0.0",
"type": "module",
"main": "./lib/",
"scripts": {
"build": "vite build"
},
"dependencies": {
"vue": "3.3.4"
}
}
// vite.config.js
import { defineConfig } from 'vite';
import { resolve } from 'path';
import pkg from './package.json';
export default defineConfig({
build: {
outDir: `RemoteDirectives/${pkg.version}`,
lib: {
entry: resolve(__dirname, 'index.js'),
name: 'RemoteDirectives',
fileName: (format) => `index.${format}.js`,
},
rollupOptions: {
output: {
globals: { vue: 'Vue' }
},
external: ['vue'],
}
}
});
// npm run build将打包后的文件放到引用工程public静态资源下,若资源加载失败,则需要在引用工程中配置代理,增加前缀代理
// 例如:
'/static': {
target: 'http://localhost:8080/otm/dvsmgt/', // 开发环境
pathRewrite: {
'^/static': '',
},
}
// app.vue
// 远程加载
const getAsyncDirectives = () =>
new Promise((resolve, reject) => {
// 模拟从远程加载指令
fetch('/static/RemoteDirectives/0.0.0/index.umd.js', {
method: 'GET',
mode: 'cors',
})
.then(response => response.text())
.then(text => {
const script = document.createElement('script');
script.text = text;
document.body.appendChild(script);
resolve();
})
.catch(reject);
});
export default {
name: 'app',
methods: {
async beforeCreate() {
await getAsyncDirectives();
this.$.appContext.app.use(window.RemoteDirectives);
console.error(this);
}
};
**********远程指令**********
console