简体   繁体   English

Vue 没有看到我的对象从 vuex 获取的更新

[英]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.我在 vuex 中有一个对象,我通过 getter 进入页面,但 vue 只看到对象的第一次更新。 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.我逐步收集对象,所以首先它是空的,然后我提交更新 vuex 状态(setUser)和 vue 在页面上显示这个新信息。 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但后来我又使用了一个提交(addInfo),它的工作原理我可以使用 Vue DevTools 看到更新的信息,但我不能在它显示第二个状态的页面上使用它

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名为 userInfo 的对象我通过

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.基本上,由于 JS 的限制,Vue 无法检测对象上的属性添加,要解决它,您的初始state.userInfo应该具有您想要具有反应性的所有键,您可以根据类型将它们设置为null''0

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.您还可以将state.userInfo = null最初设置为 null,以便您可以检测到它何时被填充。

Check here for more info of Vue Reactivity on Vue docs在此处查看有关 Vue 文档上的 Vue Reactivity的更多信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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