簡體   English   中英

如何處理Vuex存儲以從Rest API獲取數據?

[英]How to handle vuex store to fetch data from rest api?

我正在使用Vuex處理我的應用程序狀態。

我需要向rest api發出Ajax Get請求,然后顯示一些對象列表。

我正在調度一個從服務器加載此數據的操作,但是隨后我不知道如何在組件上處理它。

現在我有這個:

//component.js
created(){
      this.$store.dispatch("fetch").then(() => {
        this.objs = this.$store.state.objs;
      })
    }

但是我不認為將傳入數據分配給local屬性是處理存儲數據的正確方法。

有辦法更好地解決這個問題嗎? 也許使用mapState?

謝謝!

您可以通過多種方式來做到這一點,您必須進行試驗並找到適合自己的方法。 這是我的建議

{ // the store
  state: {
    something: ''
  },
  mutations: {
    setSomething (state, something) {
      // example of modifying before storing
      state.something = String(something)
    }
  },
    actions: {
      fetchSomething (store) {
        return fetch('/api/something')
          .then(data => {
            store.commit('setSomething', data.something)
            return store.state.something
          })
      })
    }
  }
}

{ // your component
  created () {
  this.$store
    .dispatch('fetchSomething')
    .then(something => {
      this.something = something
     })
    .catch(error => {
       // you got an error!
     })
  }
}

有關更好的解釋: https : //vuex.vuejs.org/en/actions.html

現在,如果您要處理操作本身中的錯誤,則只需調用操作並使用引用存儲中值的計算屬性即可

{
  computed: {
    something () { // gets updated automatically
      return this.$store.state.something
    }
  },
  created () {
    this.$store.dispatch('loadSomething')
  }
}

暫無
暫無

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

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