v-model 和 v-for 与 Vuex 状态下的数组一起使用

Gre*_*ett 7 javascript vue.js

我正在为选项卡式界面构建选项卡,用户可以在其中更改选项卡的标题。我想做的是这样的:

标记:

<div class="tabs" v-for="(tab, tabIndex) in tabs" :key="tab.id" >
  <input type="text" v-model:value="tabs(tabIndex)">
</div>
Run Code Online (Sandbox Code Playgroud)

计算属性:

computed: {
  scenes2: {
    get(tabIndex){
      return this.$store.state.tabs[tabIndex].title
    },
    set(value, tabIndex){
      this.$store.dispatch('setTabTitle', {value: value, tabIndex: tabIndex} )
    },
  },
},
Run Code Online (Sandbox Code Playgroud)

这当然行不通。在这里使用 v-model 的正确方法是什么,以便我可以将 Vuex 状态下v-modeltabs数组与相关索引相关联?

Ren*_*aud 6

我不会对数组和对象使用计算属性。

 <div class="tabs" v-for="(tab, tabIndex) in $store.state.tabs" :key="tab.id">
   <input type="text" :value="tab.title" @input="e => updateTabTitle(tabIndex, e)">
 </div>

methods: {
  updateTabTitle(tabIndex, event) {
    this.$store.dispatch('setTabTitle', {value: event.target.value, tabIndex} )
  }
}
Run Code Online (Sandbox Code Playgroud)

  • 这有效,谢谢。*可能*与 v 模型有关吗?有没有优先选择的情况? (2认同)
  • 也许使用 tabs 数组的本地副本(在数据中),然后在这个数组上有一个深度观察者来调度(整个数组的)更改 (2认同)