需求
要在vue的一个模块中引入远程的js,并在js加载完成之后处理一些逻辑
参考
各种搜索之后发现并没有我想要的那种解决方案,然后找了几个博客资料。感谢博主们的分享
- http://blog.youkuaiyun.com/sinat_17775997/article/details/55798611 最相似的一篇博客
- render函数两篇博客
- vue父子组件传值
创建组件
使用render函数创建一个组件,使用createElement添加dom节点。
components: { 'remote-js': { render (createElement) { var self = this return createElement('script', { attrs: { type: 'text/javascript', src: this.src }, on: { load: function () { console.log('load js') self.$emit('load-js-finish') } } }) }, props: { src: { type: String, required: true } } } },
以上是创建组件的代码。描述:创建一个script标签添加script标签的属性,监听js加载完成的事件
封装成组件方便外部调用
<template> <remote-js :src="this.jsUrl" @load-js-finish="this.jsLoadCallBack"></remote-js> </template> <script> export default { components: { 'remote-js': { render (createElement) { var self = this return createElement('script', { attrs: { type: 'text/javascript', src: this.src }, on: { load: function () { console.log('load js') self.$emit('load-js-finish') } } }) }, props: { src: { type: String, required: true } } } }, props: { jsUrl: { type: String, required: true },// 需要加载的外部url jsLoadCallBack: Function// 外部js加载完成回调 } } </script>
使用
外部调用
<template> <remote-js :js-url="'http://cdn.ronghub.com/RongIMLib-2.2.5.js'" :js-load-call-back="loadRongJs"></remote-js> </template> <script> import RemoteJs from '@/components/RemoteJs'// 导入组件 export default { components: { RemoteJs }, methods: { loadRongJs() { // 当使用远程js里的内容时请添加"//eslint-disable-line"防止eslint检测报错 console.log(RongIMLib) //eslint-disable-line } } } </script> <style> </style>
最后
希望大家多多指教