In vuex, the value I set in the index.vue component, why can't I get it in another component, crumb.vue?

topic description

I set the value of state through this.$store.dispatch in the index.vue file, and then I get the value that cannot be set through this.$store.state in another component crumb

sources of topics and their own ideas

related codes

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

in the html structure of

crumb.vue

  <span>{{city}}</span>        //

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

ask the Great God for guidance!

Jul.04,2022

the object assignment is performed directly in your mutation. In this case, vue will fail to get any changes, so try using the set method provided by vue in mutation to update the data in state.


const state = () => ({
  position: {
    city: null,
    province: null
  }
});
const mutations = {
  setPosition(state, val) {
    state.position.city = val.city;
    state.position.province = val.province;
  }
};

try it this way

Menu