发表于: 2020-06-24 23:35:48
1 1965
今日完成:
类似案例
html
<body>
<div id="app">
<!-- 需求e:当书籍栏被完全移除时,所有内容都删掉,显示购物车为空,
做判断,把之前的数据包裹,当数组有长度才显示数据,没有显示购物车为空 -->
<div v-if="books.length">
<table>
<thead>
<tr>
<th></th>
<th>书籍名称</th>
<th>出版日期</th>
<th>价格</th>
<th>购买数量</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<!-- 需求b:<tr v-for="item in books"> -->
<tr v-for="(item,index) in books">
<!-- 写法一 -->
<!-- <td v-for="value in item">{{value}}</td> -->
<!-- 需求a:写法二,因为要在某一栏添加不同操作,不添加操作效果同方法一 -->
<!-- 这里需要在价格这拼接字符串 -->
<td>{{item.id}}</td>
<td>{{item.name}}</td>
<td>{{item.data}}</td>
<!-- <td>{{'¥'+ item.price.toFixed(2)}}</td>
前面是拼接字符串,.toFixed(2)表示保留小数点后两位,不写页面显示整数 -->
<!-- 方法三,写一个计算属性 -->
<!-- <td>{{ getFinlPrice(item.price)}}</td> -->
<!-- 方法四:过滤器 -->
<td>{{ item.price | showPrice}}</td>
<td>
<!-- 需求b:,传入index -->
<button @click="decrement(index)" v-bind:disabled="item.count <=1">-</button>
<!-- 需求c:书籍购买量(count)不能为负,绑定disabled:按钮属性,不能点击
根据布尔值ture时存在,false不存在,建立表达式 -->
{{item.count}}
<button @click="increment(index)">+</button>
</td>
<td><button @click="removeHandle(index)">移除</button></td>
</tr>
</tbody>
</table>
<!-- 需求f:直接把计算属性放进来,后面是过滤器的格式 -->
<h2>总价格: {{totalPrice | showPrice}}</h2>
</div>
<h2 v-else>购物车为空</h2>
</div>
<script src="../code/vue.js"></script>
<script src="dome-7.js"></script>
</body>
css 略
js
const app = new Vue({
el: "#app",
data: {
books: [{
...
]
},
methods: {
// //方法三
// getFinlPrice(price) {//里面的参数是形参
// return '¥'+ price.toFixed(2)
// }
increment(index) { //3.所以调用要传入一个index
console.log('increment', index);
this.books[index].count++ //对应index的书本购买量加一
//需求b:1.这里注意不加分号,代码无法运行,无报错
//2.一共四栏,不管那一栏点击,打印的都是同一个,
//每本书的购买都改了,要确定每一本书的购买量,不会相互影响
},
//函数代码段之间要用逗号隔开
decrement(index) {
console.log('decrement', index);
this.books[index].count--
//这里注意不加分号,代码无法运行,无报错
},
// 需求d:移除按钮,index的作用前面提到,splice()也学过,
// 描述:点击移除数组books第index个,1代表移除自身
removeHandle(index) {
this.books.splice(index, 1)
}
},
// 需求f:求所选的总价格,做一个计算属性,计算属性本质是个属性,
// 虽然写的是个函数,只是实现了函数的get方法而已
computed: {
totalPrice() {
let totalPrice = 0 //最终价格
for (let i = 0; i < this.books.length; i++) {
totalPrice += this.books[i].price * this.books[i].count
//某一栏的价格,乘以相对应的数量
}
return totalPrice
}
},
//方法四,过滤器
filters: {
showPrice(price) {
return '¥' + price.toFixed(2)
}
}
})
评论