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

时间:2018-04-04 08:42:49

标签: vue.js vuejs2

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

这里是你玩的小提琴。 https://jsfiddle.net/50wL7mdz/265410/

HTML

  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);
      }
  }
})

VUEJS

try:
    # Python2
    import Tkinter as tk
except ImportError:
    # Python3
    import tkinter as tk

def getClipboardText():
    root = tk.Tk()
    # keep the window from showing
    root.withdraw()
    return root.clipboard_get()

提前致谢。

1 个答案:

答案 0 :(得分:3)

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

<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:{
  }
})

应始终通过更改其v模型来操作本机组件的状态,而不是进入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)
      }
    } 
  }
})