【问题标题】:How do you create modules with Vuex and get data with mapState()如何使用 Vuex 创建模块并使用 mapState() 获取数据
【发布时间】:2019-08-18 03:33:44
【问题描述】:

我尝试在模块中分离我的 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

那么,有什么问题吗? :(

【问题讨论】:

  • testStore.js 真的是按这个顺序写的吗,statemutations 在你已经尝试使用它们之后定义?您是否尝试过在 vue-devtools 中检查商店?
  • @skirtle 哦,出口是以前的,我的错,谢谢!

标签: javascript vue.js vuex


【解决方案1】:

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

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,
}

【讨论】:

    猜你喜欢
    • 2022-01-11
    • 2019-01-03
    • 2011-06-02
    • 2020-10-01
    • 2017-10-25
    • 2021-02-26
    • 2021-06-05
    • 2020-03-29
    • 2017-09-21
    相关资源
    最近更新 更多