簡體   English   中英

中間件到Vuex狀態不更新狀態?

[英]Middleware to Vuex state not updating state?

我正在嘗試獲取要存儲在狀態中的Firestore數據,但該數據不會顯示在該狀態下的Vue開發工具中。

當我console.log()通過存儲操作獲取的數據時,我可以看到獲取的數據正確,但不會更新狀態。

我在首頁和另一個頁面上使用中間件來調度我的操作,以獲取所需的數據。

我還在下面的中間件中使用了條件語句來嘗試僅在我的其他狀態變量不為null時調度操作,因為firestore查詢需要state.user

//this is check-auth middleware
 export default function(context) {
 // in initAuth we are forwarding it the req
  context.store.dispatch('initAuth', context.req)
  console.log('WE ARE GRABBING USER INFO')
  context.store.dispatch('grabUserInfo', context.req)
  console.log('There is already user info there')
  // context.store.dispatch('currentUser')
   }

我們正在調度grabUserInfo來運行其中包含firestore查詢的操作。

  grabUserInfo(vuexContext, context) {
     let userInfo = []
     var userRef = db.collection('users')
      var query = userRef
        .where('user_id', '==', vuexContext.state.user)
        .get()
        .then(querySnapshot => {
          querySnapshot.forEach(doc => {
          console.log(doc.data())
          userInfo.push(doc.data())
          })
        })
      vuexContext.commit('setUserInfoSub', userInfo)
    }

我的

   console.log(doc.data()) is showing 

訂閱者:[“ noFace2”]訂閱者:[“ noFace3”] user_id:“ VbomJvANYDNe3Bek0suySs1L8oy1”用戶名:“ noFace1”

我的信息應該經過變異並提交狀態,但不會在狀態vue開發工具中顯示。

 setUserInfoSub(state, payload) {
    state.userInfoSub = payload
  }

我不明白數據最終不會以我的狀態出現。 這是我的狀態和變異。

  const createStore = () => {
   return new Vuex.Store({
    state: {
     loadedCards: [],
     user: null,
     username: null,
     userInfoSub: [],
     token: null
   },
    mutations: {
    setCards(state, cards) {
    state.loadedCards = cards
    },
    setUser(state, payload) {
    state.user = payload
    },
     setUsername(state, payload) {
     state.username = payload
    },
    setUserInfoSub(state, payload) {
    state.userInfoSub = payload
    },
    setToken(state, token) {
    state.token = token
  }

將您的突變更改為此:

 setUserInfoSub(state, payload) {
    Vue.set(state, 'userInfoSub', payload);
    }

這將允許Vue的反應性系統重新啟動以進行狀態變量重新分配。

根據@Alexander的評論,鑒於Firebase查詢的異步性質,您還應該將commit()移到then()內。

暫無
暫無

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

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