簡體   English   中英

Vue 沒有看到我的對象從 vuex 獲取的更新

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

我在 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');
}

這就是我在頁面上得到的這就是我在頁面上得到的

這就是對象的真實樣子這就是對象的真實樣子

這是一個常見的反應性問題,有多種解決方案你會習慣的:

基本上,由於 JS 的限制,Vue 無法檢測對象上的屬性添加,要解決它,您的初始state.userInfo應該具有您想要具有反應性的所有鍵,您可以根據類型將它們設置為null''0

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

您還可以將state.userInfo = null最初設置為 null,以便您可以檢測到它何時被填充。

在此處查看有關 Vue 文檔上的 Vue Reactivity的更多信息

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM