今天要来介绍使用Vue实作出表格里的栏位选项被选择时会改变颜色

 

呈现出来的画面就会像这样

undefined

HTML

<div class="row" id="app">
  <div class="col-12" >
    <table class="table">
      <thead>
        <tr>
          <th hidden></th>
          <th>heard1</th>
          <th>heard2</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="(item,index) in itemList"
            @click="selItem(item)"
            :class="{ clicked: opened.includes(item.id) }">
          <td hidden>
            <div>
              <input type="checkbox"
                     :id="'item'+index"
                     :value="item"
                     v-model="checkedItems">
            </div>
          </td>
          <td>{{ item.id }}</td>
          <td>{{ item.name }}</td>
        </tr>
      </tbody>
    </table>
  </div>
</div>

在tbody、tr里设定click事件(selItem),以及绑定class(clicked)

然后再第一个td栏位里放input checkbox并设定成hidden


Vue

new Vue({
  el: "#app",
  data: {
    itemList:[
      { id: 1, name: 'item1', value: 1 },
      { id: 2, name: 'item2', value: 2 }
    ],
    opened:[],
    checkedItems:[]
  },
  methods:{
    selItem(item){
      const index = this.opened.indexOf(item.id);
      if(index > -1){
        this.opened.splice(index,1);
        this.checkedItems.splice(index,1);
      } else {
        this.opened.push(item.id);
        this.checkedItems.push(item);
      }
    }
  }
});

在我们设定的click事件(selItem)将opened用indexOf找寻有无id存在

如果没找到id便用push加到opened阵列里

反之indexOf找不到会回传-1那就用splice将opened阵列里的id移除


CSS

.clicked {
  background-color: #26C6DA;
}

在Html画面上我们有设定class(clicked)这边我们就设定背景颜色(background-color)

 

补充

附上CodePen

相关文章