如何使用Vuex创建模块并使用mapState()

时间:2019-08-18 03:33:44

标签: javascript vue.js vuex

我尝试将我的Vuex代码分离到模块中,但无法从mapState()获取数据。

创建模块和使用映射的最佳方法是什么?

我有一个商店文件夹:

├── store
│   └── index.js
|   └── testStore.js
|

index.js中,我有:

import Vue from "vue";
import Vuex from "vuex";

import { testStore } from './testStore'

Vue.use(Vuex);

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

testStore.js中,我有:

export const testStore  = 
{
    namespaced: true,
    state,
    mutations,
}


const state = 
{
    social: false,
    normal: true,

};
const mutations = 
{
    // setters
    setSocial(state, payload) {
      state.social = payload;
    },
    setNormal(state, payload) {
        state.normal = payload;
    },
};

我有一个测试组件可以尝试: (我使用Vuetify)

testComponent.vue

<template>
  <v-container>
    <v-layout justify-center>
        <v-btn class="primary" @click="displaydata">test</v-btn>
    </v-layout>
  </v-container>
</template>

<script>

import { mapState, mapMutations } from 'vuex'

export default {
    computed: {
        ...mapState('testStore',['normal','social']),
    },
    methods: {
        ...mapMutations('testStore',['setNormal','setSocial']),

        displaydata() {
            // eslint-disable-next-line
            console.log(this.normal);
            // eslint-disable-next-line
            console.log(this.social);
        } 
    }
};
</script>

当我单击“测试”按钮时,控制台显示:undefined

那么,怎么了? :(

1 个答案:

答案 0 :(得分:0)

这有一个非常简单的解决方案(我没看过):

testStore.js中,export const testStore在开头。

因此,右边的testStore.js非常相似,但是结尾处的export


const state = 
{
    social: false,
    normal: true,

};
const mutations = 
{
    // setters
    setSocial(state, payload) {
      state.social = payload;
    },
    setNormal(state, payload) {
        state.normal = payload;
    },
};

export const testStore  = 
{
    namespaced: true,
    state,
    mutations,
}