index.vue
<template>
<div class="hello">
<!-- 条件 -->
<p :title="title" v-if="title">{{title}}</p>
<!-- 用户输入 -->
<div>
<input type="text" v-model="text">
<button @click="addGood">添加商品</button>
</div>
<!-- 循环 -->
<ul>
<li v-for="good in goods" :key="good.id">
<span>{{good.text}}</span>
<span>¥{{good.price}}</span>
<button @click="addCart(good)">加购物车</button>
</li>
</ul>
<!-- 购物车 -->
<cart title="abc" ref="cart" @addCart="onAddCart"></cart>
</div>
</template>
<script>
import Cart from './Cart.vue';
export default {
name: 'HelloWorld',
components: {
Cart,
},
data() {
return {
title: '',
text: '',
goods: [
{id:1, text:'Web全栈架构师',price:8999},
{id:2, text:'Python全栈架构师',price:8999},
],
}
},
created(){
setTimeout(() => {
this.title = '开课吧购物车'
}, 1000);
},
methods: {
addGood() {
if (this.text) {
this.goods.push({
id: this.goods.length+1,
text: this.text,
price: 6999
});
this.text = ''
}
},
addCart(good) {
// 添加购物车
this.$refs.cart.addCart(good)
// this.$bus.$emit('addCart', good);
},
onAddCart(){
console.log('lalal');
}
},
}
<script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
<style>
Cart.vue
<template>
<table border="1">
<caption>{{title}}</caption>
<thead>
<tr>
<th></th>
<th>课程名</th>
<th>单价</th>
<th>数量</th>
<th>价格</th>
</tr>
</thead>
<tbody>
<tr v-for="c in cart" :key="c.id" :class="{inactive: !c.active}">
<td>
<input type="checkbox" v-model="c.active">
</td>
<td>{{c.text}}</td>
<td>¥{{c.price}}</td>
<td>{{c.count}}</td>
<td>¥{{c.price*c.count}}</td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="4" align="right">总计:</td>
<td>¥{{total}}</td>
</tr>
</tfoot>
</table>
</template>
<script>
export default {
data() {
return {
cart: JSON.parse(localStorage.getItem("cart")) || []
};
},
props: {
title: {
type: String,
default: ""
}
},
created() {
this.$bus.$on("addCart", good => this.addCart(good));
},
// render(createElement){
// return createElement('table', {attrs:{border:1}}, [])
// },
methods: {
addCart(good) {
// 添加购物车
const ret = this.cart.find(v => v.id === good.id);
if (ret) {
// 购物车里已有该商品
ret.count += 1;
} else {
this.cart.push({ ...good, count: 1, active: true });
}
this.$emit("addCart");
}
},
computed: {
total() {
return this.cart.reduce((sum, c) => {
if (c.active) {
sum += c.price * c.count;
}
return sum;
}, 0);
}
},
// watch: {
// cart(newValue) {
// localStorage.setItem('cart', JSON.stringify(newValue));
// }
// },
watch: {
//深度监听
cart: {
deep: true,
handler(newValue) {
localStorage.setItem("cart", JSON.stringify(newValue));
}
}
}
};
</script>
<style scoped>
.inactive {
color: gray;
}
</style>
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。