<vue 基础知识 8、购物车样例>


代码结构

一、     效果

1、 展示列表v-for

2、 购买数量增加减少,使用@click触发回调函数。

减少的时候如果已经为1了就不让继续减少,使用了v-bind绑定属性

3、 移除也是使用@click触发回调函数。

4、 总价和价格里前面增加一个¥使用了过滤器

5、 总价的计算使用了计算属性

二、代码

index.html



	
		
		index
		
	
	

		
书籍名称 出版日期 价格 购买数量 操作
{{index+1}} {{item.name}} {{item.date}} {{item.price | showPrice}} {{item.count}}
总价: {{totalPrice | showPrice}}
购物车为空

index.js

let app = new Vue({
	el: '#app',
	data: {
		list: [
			{
				id: 1,
				name: '《三国演义》',
				date: '1985-9',
				price: 100.00,
				count: 1
			},
			{
				id: 2,
				name: '《红楼梦》',
				date: '1965-2',
				price: 20.00,
				count: 1
			},
			{
				id: 3,
				name: '《西游记》',
				date: '1983-10',
				price: 30.00,
				count: 1
			},
			{
				id: 4,
				name: '《水浒传》',
				date: '1981-3',
				price: 145.00,
				count: 1
			},
		]
	},
	methods: {
		decrement(index) {
			this.list[index].count--;
		},
		increment(index) {
			this.list[index].count++;
		},
		handleRemove(index) {
			this.list.splice(index, 1);
		}
	},
	filters: {
		showPrice(value) {
			return '¥' + value.toFixed(2)
		}
	},
	computed: {
		totalPrice() {
			let total = 0;
			//方法一
			for (let i = 0; i < this.list.length; i++) {
				let item = this.list[i];
				total += item.price * item.count;
			}
			return total
		}
	}
})

style.css

table {
  border: 1px solid #e9e9e9;
  border-collapse: collapse;
  border-spacing: 0;
}

th, td {
  padding: 8px 16px;
  border: 1px solid #e9e9e9;
  text-align: left;
}

th {
  background-color: #f7f7f7;
  color: #5c6b77;
  font-weight: 600;
}
vue