实现需求:

实现一个简易的购物车,页面的表格展示data数据中的一个数组对象,并提供选中商品和全选商品checkbox复选框,页面实时显示选中商品的总金额:

vue实现CheckBox与数组对象绑定

 

分析:

1:使用v-for循环渲染arraylist对象;

2:使用computed计算属性计算总价;

3:使用computed计算全选复选框是否应该被选中(商品列表如果都被勾选,则设置全选复选框的状态为选中,否则设置全选复选框状态为取消选中);

4:根据数组中元素的初始选中状态,设置页面商品复选框是否选中。

 

代码实现:

使用html文件作为页面显示,引入js文件,Vue代码写在index.js中,页面样式保存在style.css中。

HTML:

 1 <!DOCTYPE html>
 2 <html>
 3     <head>
 4         <meta charset=utf-8>
 5         <title>Test page</title>
 6         <link rel="stylesheet" type="text/css" href="style.css">
 7     </head>
 8     <body>
 9         <div id="app" v-cloak>
10             <template v-if='list.length'>
11                 <table>
12                     <thead>
13                         <tr>
14                             <th>
15                                 <input type="checkbox" v-model="checkAll" :checked="checkAll" @change="handleCheckAll">选择
16                             </th>
17                             <th></th>
18                             <th>商品名称</th>
19                             <th>商品单价</th>
20                             <th>购买数量</th>
21                             <th>操作</th>
22                         </tr>
23                     </thead>
24                     <tbody>
25                         <tr v-for='(item, index) in list'>
26                             <td>
27                                 <input type="checkbox" v-model="item.checked" :checked="item.checked">
28                             </td>
29                             <td>{{index + 1}}</td>
30                             <td>{{item.name}}</td>
31                             <td>{{item.price}}</td>
32                             <td>
33                                 <button :disabled='item.count === 1' @click='handleReduce(index)'>-</button>
34                                 {{item.count}}
35                                 <button @click='handleAdd(index)'>+</button>
36                             </td>
37                             <td>
38                                 <button @click='handleRemove(index)'>移除</button>
39                             </td>
40                         </tr>
41                     </tbody>
42                 </table>
43                 <div>总价: {{totalPrice}}</div>
44             </template>
45             <div v-else>购物车为空</div>
46 
47         </div>
48         
49         <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
50         <script src="index.js"></script>
51     </body>
52 </html>
View Code

相关文章:

  • 2021-04-09
  • 2021-08-02
  • 2022-12-23
  • 2021-07-05
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-05-23
  • 2021-07-06
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-04-06
相关资源
相似解决方案