题目描述
我在index.vue文件中通过 this.$store.dispatch设置了 state的值,然后我在另外一个组件crumb中通过this.$store.state获取不到设置的值
题目来源及自己的思路
相关代码
index.vue
async mounted() {
let self = this
console.log(self.$store.state.geo.position); // 数据为空
// 设置当前城市和省份
self.$store.dispatch(
"geo/setPosition",
{
city: window.localStorage.getItem("currentCity"),
province: window.localStorage.getItem("currentPro")
}
);
console.log(self.$store.state.geo.position); //有数据
crumb.vue
computed: {
city() {
return this.$store.state.geo.position.city;
}
},
crumb.vue的html结构中使用
{{city}} //为空
geo.js
const state = () => ({
position: {}
});
const mutations = {
setPosition(state, val) {
state.position = val;
}
};
const actions = {
setPosition: ({ commit }, position) => {
commit("setPosition", position);
}
};
export default {
namespaced: true,
state,
mutations,
actions
};
index.js
import Vue from "vue";
import vuex from "vuex";
import geo from "./modules/geo";
Vue.use(vuex);
const store = () =>
new vuex.Store({
modules: {
geo,
},
});
export default store
求大神指点指点!