VueJS 通过单击表格行触发复选框

Sam*_*ong 1 vue.js vuejs2

我对 vuejs 很陌生,我想知道是否可以通过单击表格行来触发复选框。

这是一把小提琴供你演奏。 https://jsfiddle.net/50wL7mdz/265410/

超文本标记语言

<div id="app">
<table>
    <tbody>
      <tr v-for="cat in categories" @click="selectCat(cat)">
        <td><input type="checkbox" :value="cat" v-model="selected" name="" id=""></td>
        <td>{{ cat.code}}</td>
        <td>{{ cat.name }}</td>
      </tr>
    </tbody>
</table>
<button @click="checkData()">Check</button>
</div>
Run Code Online (Sandbox Code Playgroud)

虚拟联合体

  new Vue({
  el: '#app',
  data() {
    return {
     categories: [
                {code:'HW', name:'Hardware'},
          {code:'SW', name:'Software'},
          {code:'OS', name:'Office Supplies'}
     ],
     selected:[]
    }
  },
  methods:{ 
  selectCat(cat){
    this.selected.push(cat);
  },
 checkData(){
      alert(1);
       console.log(this.selected);
      }
  }
})
Run Code Online (Sandbox Code Playgroud)

提前致谢。

Phi*_*ann 5

将选定的模型添加到您的类别中,然后在行单击上切换该属性,如下所示:

<div id="app">
    <table>
        <tbody>
          <tr v-for="(cat, index) in categories" :key="index" @click="cat.selected = !cat.selected">
            <td><input type="checkbox" v-model="cat.selected"></td>
            <td>{{ cat.code}}</td>
            <td>{{ cat.name }}</td>
          </tr>
        </tbody>
    </table>
</div>


new Vue({
  el: '#app',
  data() {
    return {
     categories: [
                {code:'HW', name:'Hardware', selected: false},
          {code:'SW', name:'Software', selected: false},
          {code:'OS', name:'Office Supplies', selected: false}
     ]
    }
  },
  methods:{
  }
})
Run Code Online (Sandbox Code Playgroud)

操作本机组件的状态应始终通过更改其 v-model 来完成,而不是进入 DOM 并设置选定的属性。基本上让你的模型定义你的视图的状态。

这是另一个版本,它将使用单独的数组来处理选定的状态:

<div id="app">
    <table>
        <tbody>
          <tr v-for="(cat, index) in categories" :key="index" @click="toggleSelect(cat)">
            <td><input type="checkbox" :checked="selected.includes(cat.code)"></td>
            <td>{{ cat.code}}</td>
            <td>{{ cat.name }}</td>
          </tr>
        </tbody>
    </table>
</div>

new Vue({
  el: '#app',
  data() {
    return {
     categories: [
          {code:'HW', name:'Hardware'},
          {code:'SW', name:'Software'},
          {code:'OS', name:'Office Supplies'}
     ],
     selected: ['HW']
    }
  },
  methods:{
    toggleSelect (cat) {

      if (this.selected.includes(cat.code)) {
        this.selected.splice(this.selected.findIndex(v => v === cat.code), 1)
      } else {
        this.selected.push(cat.code)
      }
    } 
  }
})
Run Code Online (Sandbox Code Playgroud)