【优化过往代码】关于vue自定义事件的运用
- 需求说明
- 过往代码
- 优化思路
- 优化后代码(Vue2)
- 遇到问题记录
Vue2官方自定义指令说明文档
Vue3官方自定义指令说明文档
需求说明
- 进入某些页面需要加载一些外部资源,并在资源加载完后进行一些处理;
- 离开页面时要将资源移除掉
过往代码
<script>
export default {mounted() {// OpenInstalllet _that = this;const s = document.createElement("script");s.type = "text/javascript";s.src = "//web.cdn.openinstall.io/openinstall.js";s.setAttribute("data-callType", "callScript");s.addEventListener("load",() => {var data = OpenInstall.parseUrlParams();console.log(data, "OpenInstall");new OpenInstall({appKey: process.env.appKey, //appkey参数配置,需要自行替换对应的appkeyonready: function () {// ... 一些逻辑},},data);},false);document.head.appendChild(s);},beforeDestroy() {let callScript = document.querySelector("script[data-callType='callScript']");document.head.removeChild(callScript);},
};
</script>
优化思路
定义一个全局指令
- 指令放在页面根节点上
- 将资源的加载放到指令里进行,这里把script标签放在绑定元素下(即页面根节点),在页面切换时就不用手动移除script标签
- 资源加载后的处理逻辑作为指令的绑定值传给传给指令,再由指令去调用
优化后代码(Vue2)
main.js:
// 注册一个全局自定义指令 `v-openinstall`
Vue.directive('openinstall', {inserted: function (el, binding) {const s = document.createElement("script");s.type = "text/javascript";s.src = "//web.cdn.openinstall.io/openinstall.js";s.setAttribute("data-callType", "callScript");s.addEventListener("load",() => {binding.value();},false);el.appendChild(s);console.log(el);},
})
组件内:
<template><div v-openinstall="openinstallHandler"><h1>测试自定义指令</h1><button id="downloadButton">按钮</button></div>
</template><script>
export default {name: "download", // 下载页methods: {openinstallHandler(){console.log('OpenInstall资源加载完成',OpenInstall);var data = OpenInstall.parseUrlParams();console.log(data, "OpenInstall.parseUrlParams()获取链接参数");new OpenInstall({appKey: 'xxx',onready: function () {var m = this,button = document.getElementById("downloadButton");button.onclick = function () {m.wakeupOrInstall({data: {}});return false;};}},data);},go(){this.$router.push({path:'/'})}}
}
</script>
遇到问题记录
开发过程中如果报错 ‘OpenInstall‘ is not defined
,参考 Vue 项目报错:‘XXXXX‘ is not defined ( no-undef ) 解决方法 可以解决