简体   繁体   English

如何在vue.js项目的main.js文件中导入js类并在所有组件中使用它,而不是在每个组件中导入?

[英]How to import a js class in main.js file of a vue.js project and use it in all the components instead of importing in each component?

I have written some JS classes that I would like to import in the app.js/main.js file of my vue.js project so that I can instantiate them in the components. 我已经写了一些JS类,我想将它们导入vue.js项目的app.js / main.js文件中,以便可以在组件中实例化它们。 Right now I am having to import the same JS class in all the components where I need the class individually. 现在,我必须在需要单个类的所有组件中导入相同的JS类。

I've tried the import in the main.js file but the components don't recognize it. 我已经尝试了main.js文件中的导入,但是组件无法识别它。

in the main.js file, I am importing like as follows 在main.js文件中,我按如下方式导入

import Permissions from './Permissions'

However, when I want to instantiate the Permissions class in my component like 但是,当我想在我的组件中实例化Permissions类时

data() { permissions: new Permission({ some object properties... }) }

the component doesn't know what Permissions is. 该组件不知道什么是Permissions

How do I let the component know what Permissions class is? 如何让组件知道Permissions类是什么?

To do it in the vue way, you can create your own plugin or mixin. 为此,您可以创建自己的插件或mixin。 See detailed instructions here 在这里查看详细说明

So, you can create a permissions plugin in permissions-plugin.js 因此,您可以在Permissions-plugin.js中创建一个权限插件

import Permissions from './Permissions'

const PermissionsPlugin = {
  install(Vue, options) {
    // This adds the $getPermissions method to all instances
    Vue.prototype.$getPermissions = function(properties) {
      return new Permission({
        some object properties...
      })   
    }
  }
};

Then you have to tell vue to use your plugin: 然后,您必须告诉vue使用您的插件:

import Vue from 'vue'
import PermissionsPlugin from './permissions-plugin.js'
import App from './App.vue'

// The plugin is loaded here.
Vue.use(PermissionsPlugin)

new Vue({
  el: '#app',
  render: h => h(App)
});

And lastly now from any component you should be able to use your function like: 最后,现在从任何组件开始,您都可以使用如下功能:

this.$getPermissions(properties)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM