javascript - 如何使用 Vuex 创建模块并使用 mapState() 获取数据
问题描述
我尝试在模块中分离我的 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
,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,
}
推荐阅读
- python - 根据不同列中的值替换特定列中的熊猫数据框值
- javascript - 使用 jQuery 将元素写入 textarea
- php - 返回pdf文件的页数时出错
- oracle - 分页数据,但将组保持在同一页面上
- google-cloud-functions - 有没有办法检查 firebase 函数上次运行的时间?
- angular - 如何在动态创建的组件中注入服务的唯一实例?
- regex - 如何使用 ruby 删除连续的换行符 \n 实例
- java - 排除数组的第一个和最后一个元素
- odoo - 如何替换 store=true odoo 14?
- algorithm - 用 polyominos 填充一个矩形