Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

vue-cli 引入外部 JS 库的两种方式 #36

Closed
Dream4ever opened this issue Jun 6, 2018 · 0 comments
Closed

vue-cli 引入外部 JS 库的两种方式 #36

Dream4ever opened this issue Jun 6, 2018 · 0 comments
Labels
Front-end Everything you see and experience JS Javascript Vue Powerful framework

Comments

@Dream4ever
Copy link
Owner

Dream4ever commented Jun 6, 2018

需求描述

在业务开发中,需要将各种 JS 库引入 vue-cli 中。有两种方式可以实现需求,一种是在 main.js 中全局引入,另一种则是在指定的组件中局部引入。

方案调研

调研过程

因为需要在 vue-cli 中引入 hls.js 这个库,所以用 vue/vue-cli + hls/hls.js 进行 Google,找到了解决方案。

入选方案

应用过程

全局引用

// main.js
// 先引入这个库
import hlsjs from 'hls.js';

// 然后挂载到 Vue 实例的原型上
Object.defineProperty(Vue.prototype, 'Hls', { value: hlsjs });
// 或
Vue.prototype.Hls = hlsjs;

// 在组件中使用时
// App.vue
if (this.Hls.isSupported()) { ... }

局部引用

// App.vue
import hlsjs from 'hls.js';
window.Hls = hlsjs;

if (Hls.isSupported()) { ... }

注意

所引用的外部库,不要求非得在当前项目所在的目录之内,完全可以是项目之外的某个文件。不过如果是不同分区上的文件(对于 Windows 系统来说),就不知道了。而且把代码放到两个分区,这个习惯不大好吧。

// e:\codebase\utils\addcnzz.js
const AddCnzz = () => {
  const hostName = window.location.hostname;
  const sites = [
    {
      domain: 'abc',
      id: '123',
    },
    {
      domain: 'def',
      id: '456',
    },
  ];
  const site = sites.find(ele => hostName.match(ele.domain)) || null;
  if (site) {
    const script = document.createElement('script');
    script.src = `https://s11.cnzz.com/z_stat.php?id=${site.id}&web_id=${site.id}`;
    document.body.appendChild(script);
  }
}

export default AddCnzz;
// App.vue
import AddCnzz from '../codebase/utils/addcnzz';

created() {
  AddCnzz();
}

要点总结

如果所引入的 JS 库需要在各个组件中都用到,那么建议用全局引用的方式。否则就用局部引用的方式,而且局部引用之后,可以直接调用该 JS 库的实例,不用加 this 关键字。

@Dream4ever Dream4ever added Front-end Everything you see and experience JS Javascript Vue Powerful framework labels Jun 6, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Front-end Everything you see and experience JS Javascript Vue Powerful framework
Projects
None yet
Development

No branches or pull requests

1 participant