首页 > 解决方案 > 如何处理 vuex 存储以从 rest api 获取数据?

问题描述

我正在使用 Vuex 来处理我的应用程序状态。

我需要向 rest api 发出 Ajax Get 请求,然后显示一些对象列表。

我正在调度一个从服务器加载此数据的操作,但是我不知道如何在组件上处理它。

现在我有这个:

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

但我不认为将传入数据分配给本地属性是处理存储数据的正确方法。

有没有办法更好地处理这个问题?也许使用mapState?

谢谢!

标签: javascriptvue.jsvuex

解决方案


There are many ways you can do it, you must experiment and find the one that fits your approach by yourself. This is what I suggest

{ // 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!
     })
  }
}

For better explanations: https://vuex.vuejs.org/en/actions.html

Now, if you're handling the error in the action itself, you can simply call the action and use a computed property referencing the value in the store

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

推荐阅读