【问题标题】:Vue doesn't see updates of my object getting from vuexVue 看不到我的对象从 vuex 获取的更新
【发布时间】:2021-10-16 02:54:32
【问题描述】:

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

被称为 userInfo 的对象我正在通过该页面访问

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

这是我在页面上看到的

这就是对象的真实样子

【问题讨论】:

  • 请把你的变异函数(addInfo)放在这里
  • 并添加您的 getter 函数以确保完整性
  • 我的变异函数:addInfo(state, additionalInfo) { Object.assign(state.userInfo, additionalInfo);我的吸气剂: userInfo: (state) => state.userInfo

标签: javascript vue.js vuex single-page-application getter


【解决方案1】:

这是一个常见的反应性问题,有多种解决方案你会习惯的:

由于 JS 的限制,基本上 Vue 无法检测到对象上的属性添加,要解决这个问题,您的初始 state.userInfo 应该具有您想要具有反应性的所有键,您可以将它们设置为 null、'' 或0 取决于类型。

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

您还可以将 state.userInfo = null 初始设置为 null,以便您可以检测到它何时被填充。

点击此处了解Vue Reactivity on Vue docs的更多信息

【讨论】:

  • 我尝试了所有这些,但没有帮助。我的控制台中仍然有完整的对象,但页面上没有任何变化。
  • 但是我尝试这样做 this.someObject = Object.assign({}, this.someObject, { a: 1, b: 2 }) 就像 Vue 文档中所说的那样,它的工作原理。非常感谢!
猜你喜欢
  • 2021-06-17
  • 2018-02-04
  • 2021-05-08
  • 2019-10-19
  • 2019-08-06
  • 2020-06-01
  • 1970-01-01
  • 2019-04-10
  • 2021-12-25
相关资源
最近更新 更多