简体   繁体   English

如何在 vue 中导入外部模块?

[英]How to import external module in vue?

My code below is working fine:我下面的代码工作正常:

import Vue from 'vue';
import Vuex from 'vuex';

import user from './modules/auth';

Vue.use(Vuex);

export default new Vuex.Store({
    modules: {
        user
    }
 });

Is there a shorter way to import a module instead of writing the statement at the top?有没有更短的方法来导入模块而不是在顶部编写语句? I instead write it directly inside the modules like below:我改为直接在模块中编写它,如下所示:

export default new Vuex.Store({
    modules: {
        user: import('./modules/auth'),
    }
 });

But unfortunately it didn't work (the external module was not imported successfully).但不幸的是它没有工作(外部模块没有成功导入)。

Import with braces is different from import without braces - the latter imports the module statically (at compile time) while the former imports the module dynamically (at run time) and is not an ES6 feature but something specific to Webpack.带大括号的Import与不带大括号的import不同——后者静态导入模块(在编译时),而前者动态导入模块(在运行时),这不是 ES6 特性,而是 Webpack 特有的东西。

You can read more in the Webpack documentation but the most important thing is that dynamic imports (those with braces) return a Promise instead of module reference.您可以在Webpack 文档中阅读更多内容,但最重要的是动态导入(带有大括号的)返回Promise而不是模块引用。 The module reference will be available when the Promise resolves.当 Promise 解析时,模块参考将可用。 You can read more about lazy-loading Vuex modules in this article https://itnext.io/vue-js-app-performance-optimization-part-3-lazy-loading-vuex-modules-ed67cf555976您可以在这篇文章https://itnext.io/vue-js-app-performance-optimization-part-3-lazy-loading-vuex-modules-ed67cf555976中阅读有关延迟加载 Vuex 模块的更多信息

Before beginning, I'm using Vue 3 + Vuex 4.在开始之前,我使用的是 Vue 3 + Vuex 4。

In the file path/to/store/index.js that hold the Vuex store I used the code like this.在包含 Vuex 存储的文件 path/to/store/index.js 中,我使用了这样的代码。

// path/to/store/index.js
import { createStore } from 'vuex';
import moduleA from './modules/moduleA';
import moduleB from './modules/moduleB';

export default createStore({
  state: {},
  mutations: {},
  getters: {},
  actions: {},
  modules: {
    moduleA,
    moduleB,
  },
});

And I created a file for each module as this我为每个模块创建了一个文件,因为

// file for each module
export default {
  state: { ... },
  mutations: { ... },
  getters: { ... },
  actions: { ... },
  modules: { ... },
};

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

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