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

全選反選-vue

全選反選-vue
<template>
  <div>
    <table>
      <tr>
        <th><input type="checkbox" v-model="selectAll" />全選/全不選</th>
        <th v-for="(item, index) in titles" :key="index">{{ item }}</th>
      </tr>
      <tr v-for="(item, index) in books" :key="item.name">
        <td><input type="checkbox" v-model="item.select" /></td>
        <td>{{ index }}</td>
        <td>{{ item.name }}</td>
        <td>{{ item.date }}</td>
        <td>¥{{ item.price.toFixed(2) }}</td>
        <td>
          <button @click="redu(index)">-</button>
          {{ item.num }}
          
<button @click="add(index)">+</button> </td> <td><button @click="del(index)">移除</button></td> </tr> <tr> <td colspan="7" style="text-align: left">總價格為:{{ total }}</td> </tr> </table> </div> </template> <script> export
default { data() { return { titles: ["編號", "書籍名稱", "出版日期", "價格", "數量", "操作"], books: [ { name: "演算法導論", date: "2006-9", price: 85, num: 1, select: true, }, { name: "UNIX程式設計藝術", date: "2006-2", price:
59, num: 1, select: true, }, { name: "Vue程式設計", date: "2008-10", price: 35, num: 1, select: true, }, { name: "頸椎康復", date: "2006-3", price: 129, num: 1, select: true, }, ], }; }, computed: { total() { let ret = this.books.reduce((pre, cur) => { return cur.price * cur.num + pre; }, 0); return "¥" + ret.toFixed(2); }, selectAll: { get() { for (let i = 0; i < this.books.length; i++) { if (!this.books[i].select) { return false; } } return true; }, set(newVal) { this.books.forEach((item) => { item.select = newVal; }); }, }, }, methods: { add(i) { if (!this.books[i].select) { alert("你還沒做出選擇"); return; } this.books[i].num++; }, redu(i) { if (!this.books[i].select) { alert("你還沒做出選擇"); return; } this.books[i].num > 1 ? this.books[i].num-- : ""; }, del(i) { if (!this.books[i].select) { alert("你還沒做出選擇"); return; } this.books.splice(i, 1); }, }, }; </script> <style lang = "less" scoped> table { border-collapse: collapse; margin: 100px auto; } table, td, th { border: 1px solid #000; } td, th { padding: 10px; } </style>