首页 > 解决方案 > 在 vue.js 中获取具有动态行的表中的选择标记值

问题描述

我想在 VM 数据中设置选择标签的值。

<table id="vm" v-cloak>
  <thead>
    <tr>
      <th>Select</th><th>Operation</th>
    </tr>
  </thead>
  <tbody>
    <tr v-for="(item, i) in rowData">
      <td>
        <select v-model="selected" @change="changeDate($event)">
          <option v-for="sItem in selectItems" :value="sItem.val">{{sItem.lbl}}</option>
        </select>
      </td>
      <td>
        <button @click="addRow(i)">+</button>
        <button @click="removeRow(i)">-</button>
      </td>
    </tr>
  </tbody>
</table>

我的剧本

// Select tag items
const SELECT_ITEMS = [
  {val:"1", lbl:"Val1"},
  {val:"2", lbl:"Val2"},
  {val:"3", lbl:"Val3"}
];

// my vm
new Vue({
  el: "#vm",
  data:{
    rowData:[{val:"1"},{val:"2"}],
    selected : '',
    selectItems : SELECT_ITEMS
  },
  methods:{
    // add new row
    addRow(i){
      let row = {
        val : this.selected,
      };
      this.rowData.splice(i, 0, row);
      this.val = '';
    },
    // remove current row
    removeRow(i){
      this.rowData.splice(i,1);
    },
    changeDate(e){
      // I want to set a value to item in rowData.
      console.log(e.target.value);
    }
  }
});

代码笔

不知道如何将选中的数据设置为rowData当前行的数据。

而且,更改一项会更改所有项目。

而且,我想在加载时添加选定的属性。

标签: javascriptvue.jsvuejs2

解决方案


为什么不直接使用rowDatain v-model

演示

<tr v-for="(item, i) in rowData">
  <td>
    <select v-model="rowData[i].val" @change="changeDate($event)">
      <option v-for="sItem in selectItems" :value="sItem.val">{{sItem.lbl}}</option>
    </select>
  </td>
  <td>
    <button @click="addRow(i)">+</button>
    <button @click="removeRow(i)">-</button>
  </td>
</tr>

推荐阅读