1. 程式人生 > 其它 >全選反選-vue 2.0

全選反選-vue 2.0

全選反選 2.0
<template>
  <div>
    <table>
        <tr>
          <th><input type="checkbox" v-model="isCheckAll">全選/全不選</th>
          <th v-for="item in titles" :key="item">{{item}}</th>
        </tr>
        <tr v-for="item,index in books" :key="index"
> <td><input type="checkbox" v-model="checkList[index]"></td> <td>{{item.name}}</td> <td>{{item.date}}</td> <td>{{ '¥'+item.price.toFixed(2)}}</td> <td> <button @click="red(index)"
>-</button> {{item.num}} <button @click="add(index)">+</button> </td> <td><button @click="del(index)">移除</button></td> </tr> <tr> <td colspan="6" style="text-align: right;"
>總價:{{total}}</td> </tr> </table> </div> </template> <script> export default { data () { return { // checkList儲存每一項的勾選情況 checkList:[], // isCheckAll:true, titles: ['書籍名稱', '出版日期', '價格', '數量', '操作'], books: [ { name: '演算法導論', date: '2006-9', price: 85, num: 1 }, { name: 'UNIX程式設計藝術', date: '2006-2', price: 59, num: 1 }, { name: 'Vue程式設計', date: '2008-10', price: 35, num: 1 }, { name: '頸椎康復', date: '2006-3', price: 129, num: 1 }, ] } }, created(){ // 根據books有多少項,決定checkList this.checkList = this.books.map(()=>false); }, computed:{ // isCheckAll來表示 全選按鈕是否被勾上 isCheckAll:{ get(){ // 特點: 返回true就勾上,false就沒有勾上 // 看isCheckAll 和 checkList的關係 // checkList只要有一個為false ( 包含false ), isCheckAll就要返回false return !this.checkList.includes(false) }, set(newVal){ // 使用者點選全選按鈕,會觸發這個方法的執行 console.log(newVal); // 把checkList裡面的值都改成新的值newVal this.checkList = this.checkList.map(()=>newVal); } }, total(){ let ret = this.books.reduce((pre,cur,index)=>{ // index 當前這一項的下標/索引 // if(這一項(checkList對應的這一項是不是為true)有沒有打勾){ if(this.checkList[index]){ return cur.price*cur.num + pre }else{ return pre } },0) return ''+ret.toFixed(2)+ "" } }, methods:{ del(i){ // 刪除books的元素的同時, 刪除checkList的元素 this.books.splice(i,1); this.checkList.splice(i,1); }, add(i){ this.books[i].num++ }, red(i){ if(this.books[i].num>1){ this.books[i].num-- } } } } </script> <style lang = "less" scoped> *{ padding: 0; margin: 0; list-style: none; } table,td,th{ border: 1px solid #000; } table{ border-collapse: collapse; /* margin: auto; */ } th,td{ padding: 10px; } </style>