首页 > 解决方案 > Vuex:对象数组元素的表单绑定?

问题描述

Vuex 有很好的文档。我们在其中看到了如何进行2 向绑定

// component.vue
...,
computed: {
  message: {
    get () {
      return this.$store.state.obj.message
    },
    set (value) {
      this.$store.commit('updateMessage', value)
    }
  }
},
...

这很好用,但是如果你想绑定数组对象的属性怎么办?

例如

// state.js
...
listOfThings: [
    {
        text: 'lets bind this',
        value: 0
    },
    {
        text: 'and this is in the $store',
        value: 20
    }
]

假设我们使用mapState,那么我们可能希望有一个组件用于用户可以更新商店的事物列表:

或者,是实现此目的的唯一方法,方法是使对象的表单绑定成为其自己的组件,并通过道具传入索引并在表单组件中使用

 text: {
    get () {
      return this.$store.state.listOfThings[this.i].text
    },
    set (value) {
      this.$store.commit('updateText', {i, text: value})
    }
  }

标签: vuejs2vuexvuex-modules

解决方案


推荐阅读