简体   繁体   中英

Vue doesn't see updates of my object getting from vuex

I have an object in vuex that im getting on the page by getters, but vue see only first update of object. I collect the object stepwise so first it's empty then i have commit that updates vuex state (setUser) and vue showing this new info on the page. But then i use one more commit (addInfo) and it's works I can see updated info using Vue DevTools, but i can't use it on the page it's showing second state

async fetchUser({ commit, state }) {
  return new Promise(() => {
    axiosInstance
      .get(User(), {
        headers: {
          Authorization: 'Token ' + localStorage.getItem('token'),
        },
      })
      .then((res) => {
        commit('setUser', res.data);
      })
      .then(() => {
        axiosInstance.get(UserID(state.userInfo.pk)).then((res) => {
          axiosInstance.get(res.data.profile).then((res) => {
            commit('addInfo', res.data);
            console.log(state.userInfo);
          });
        });
      })
      .catch((err) => {
        console.log(err);
      });
  });
}

Object called userInfo im getting on the page by

computed: {
    ...mapGetters(['userInfo']),
},
created() {
    this.$store.dispatch('fetchUser');
}

This is what i get on the page这就是我在页面上得到的

This is how the object really looks like这就是对象的真实样子

This is a common reactivity issue, there are multiple solutions on you'll get used to it:

Basically Vue can not detect property addition on objects due to JS limitations, to solve it your initial state.userInfo should have all keys you want to have reactivity, you can just set them to null , '' , or 0 depending on type.

userInfo: {
//all my userInfo reactive keys
 1stkey: '',
 2ndkey: null,
 3rdkey: 0,
 ...
 100thkey: '',
}

You can also set your state.userInfo = null initially to null so you can detect when it gets filled.

Check here for more info of Vue Reactivity on Vue docs

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM