Vue 中如何正确引入第三方模块

栏目: JavaScript · 发布时间: 6年前

内容简介:假设要使用到 jquery,那么可以通过配置 webpack 的 ProvidePlugin 的插件来全局引入:

Vue 中如何正确引入第三方模块

Vue 中如何正确引入第三方模块

方法一:配置 webpack ProvidePlugin 全局引入

假设要使用到 jquery,那么可以通过配置 webpack 的 ProvidePlugin 的插件来全局引入:

https://webpack.js.org/plugin...

new webpack.ProvidePlugin({
  $: 'jquery',
  jQuery: 'jquery'
})

方法二:包装成插件在 Vue 中调用 use 方法安装

另外一种比较靠谱的方法是将第三方模块打包成插件,如我需要全局使用 echarts,那么在 src 目录下新建一个 lib,并创建名为 echarts.js 的文件:

import echarts from 'echarts'

export default {
  install (Vue) {
    Object.defineProperty(Vue.prototype, '$echarts', {
      value: echarts
    })
  }
}

上述代码 export 一个对象,对象包含一个 install 方法,该方法的参数是 Vue 构造函数,我们使用 Object.defineProperty 或 Reflect 的方法将 $echarts 定义到 Vue.prototype 中去。

然后在项目中使用:

import echarts from './lib/echarts'

Vue.use(echarts) // use

new Vue({
    // ...
}).$mount('#app')

这样就可以在 vue 实例中通过 $echarts 来使用

// ...
let myChart = this.$echarts.init(this.$refs.main)
// ...

其他方法

其他还有在 window 对象中全局定义;或使用 Vue.prototype.xxx = xxx 等,都存在各样问题,如 window 会导致全局作用域污染;后者定义方式不可靠,比方说 echarts 模块太大,会经常出现扩展定义失败导致的报错

Vue 中如何正确引入第三方模块

请关注我的订阅号,不定期推送有关 JS 的技术文章,只谈技术不谈八卦 :blush:


以上所述就是小编给大家介绍的《Vue 中如何正确引入第三方模块》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Ethnography and Virtual Worlds

Ethnography and Virtual Worlds

Tom Boellstorff、Bonnie Nardi、Celia Pearce、T. L. Taylor / Princeton University Press / 2012-9-16 / GBP 21.00

"Ethnography and Virtual Worlds" is the only book of its kind - a concise, comprehensive, and practical guide for students, teachers, designers, and scholars interested in using ethnographic methods t......一起来看看 《Ethnography and Virtual Worlds》 这本书的介绍吧!

MD5 加密
MD5 加密

MD5 加密工具

SHA 加密
SHA 加密

SHA 加密工具

XML 在线格式化
XML 在线格式化

在线 XML 格式化压缩工具