首页 > 解决方案 > Vuejs - vuex lazy load

问题描述

I have a fairly large VueJS SPA, and I just wanted to load the vuex modules on certain routes, using the lazy load.

I was following this article to reproduce this - https://alexjoverm.github.io/2017/07/16/Lazy-load-in-Vue-using-Webpack-s-code-splitting/

However this is giving me an error in vuex.

Folder structure

root
  |- store
  | |- modules
  | | |- auth.js
  | | |- module2.js
  | |- store.js
  |- app.js

auth.js

const state = {
    var1: {},
    var2: false
}

const mutations = {
    'MUTATION_1'(state, obj) {
        // logic
    }
}

const actions = {
    action1({commit}) {
       // logic
    }
}

const getters = {
    var1: state => state.var1,
    var2: state => state.var2
}

export default {
    state,
    mutations,
    actions,
    getters
}

store.js -

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

Vue.use(Vuex);
const store = new Vuex.Store();

import('./modules/auth.js').then(auth => {
    store.registerModule('/login', auth);
});

export default store;

app.js -

import Vue from 'vue';
import store from './store/store';
import VueRouter from 'vue-router';
import { routes } from './routes/routes';

// vue-router config
Vue.use(VueRouter);

const router = new VueRouter({
    mode: 'history',
    routes
});

const app = new Vue({
    el: '#app',
    store,
    router
});

error -

[vuex] unknown getter: var1

Any suggestion?

标签: vue.jsvuejs2vue-routervuex

解决方案


store.registerModule('/login', auth);

上面的代码使用 soauth的命名空间注册模块,login以便从存储中访问其状态、getter、突变和操作,您必须在所有这些前面加上 path login/。您收到错误是因为您可能store.getters.var1在应该调用store.getters['login/var1'].


推荐阅读