首页 > 解决方案 > 通过 Vue Computed Setter 调用 Vuex Action

问题描述

我有一个存储在 Firebase 中的计数器的值。

{
  name: 'sheep',
  total: 0
}

我使用调用 Firebase 的操作将其同步到 Vuex 状态的值。

loadedCounter ({ commit }) {
  commit('setLoading', true)
  firebase.database().ref('animals').on('value', (snapshot) => {
    let counter = []
    let obj = snapshot.val()
    for (let key in obj) {
      counter.push({
        name: obj[key].name,
        total: obj[key].total
      })
    }
    commit('setLoadedCounter', test)
    commit('setLoading', false)
  })
},

然后我在我的 Vue 组件中使用一个computed属性来获取值。吸气剂正在工作。

computed: {
sheepCounter: {
  get () {
    let test = this.$store.getters.getSheep
    return test.total
  },
  set (value) {
    this.$store.commit('updateSheep', value)
  }
}

但是二传手出错了。我在控制台中收到此错误:

[vuex] 未知突变类型:updateSheep

我认为问题在于该集合只能引用一个突变并且updateSheep是一个action. 但据我了解,它必须是一个动作,因为它是异步代码。

updateSheep ({commit}, payload) {
  firebase.database().ref('animals').child('sheep').update({total: payload})
},

如何使用同步到 Firebase 的计算机属性集来设置数据?

标签: vue.jsfirebase-realtime-databasevuejs2vuex

解决方案


我能够通过调度操作来解决这个问题。我试图采取行动。调度是为了行动:

this.$store.dispatch('updateSheep', value)

不是

this.$store.commit('updateSheep', value)

推荐阅读