非组件写法:
App.vue:
<template>
<div>
<h1>hello {{ title }} 常规 非组件化</h1>
<ul>
<li v-for="(good, index) in goods" :key="good.text">
{{ good.text }}
|
{{ good.price }}
<button @click="addCart(index)">添加购物车</button>
</li>
</ul>
<table border="1">
<tr>
<td>商品</td>
<td>单价</td>
<td>价格</td>
<td>总量</td>
<td>操作</td>
</tr>
<tr v-for="(c, index) in cart" :key="index">
<td>{{ c.text }}</td>
<td>{{ c.price }}</td>
<td>{{ c.price * c.count }}</td>
<td>{{ c.count }}</td>
<td></td>
</tr>
</table>
</div>
</template>
<script>
export default {
data() {
return {
title: "china",
goods: [
{ text: "高薪架构师", price: 100 },
{ text: "高薪全栈", price: 90 },
{ text: "高薪架高级", price: 30 }
],
cart: []
};
},
methods: {
addCart(i) {
console.log("添加购物车");
let item = this.goods[i];
let good = this.cart.find(v => v.text == item.text);
if (good) {
good.count += 1;
} else {
this.cart.push({ ...item, count: 1 });
}
}
}
};
</script>
<style scoped>
h1 {
color: red;
}
</style>
提取组件写法:(未使用elementUI,提取了一个cart.vue组件)
<template>
<div>
<h1>hello {{ title }}制作的原生组件</h1>
<ul>
<li v-for="(good, index) in goods" :key="good.text">
{{ good.text }}
|
{{ good.price }}
<button @click="addCart(index)">添加购物车</button>
</li>
</ul>
<Cart :data="cart" @addF="onAdd" @reduceF="onReduce"></Cart>
</div>
</template>
<script>
import Cart from "./components/Cart";
export default {
components: {
Cart
},
data() {
return {
title: "china",
goods: [
{ text: "高薪架构师", price: 100 },
{ text: "高薪全栈", price: 90 },
{ text: "高薪架高级", price: 30 }
],
cart: []
};
},
methods: {
addCart(i) {
console.log("添加购物车");
let item = this.goods[i];
let good = this.cart.find(v => v.text == item.text);
if (good) {
good.count += 1;
} else {
this.cart.push({ ...item, count: 1 });
}
},
onAdd(arg) {
let { index } = arg;
this.cart[index].count += 1;
},
onReduce(arg) {
let { index } = arg;
if (this.cart[index].count > 1) {
this.cart[index].count -= 1;
}
}
}
};
</script>
<style scoped>
h1 {
color: red;
}
</style>
cart组件 commponets>cart.vue:
<template>
<div>
<h2>购物车</h2>
<table border="1">
<tr>
<td>商品</td>
<td>单价</td>
<td>价格</td>
<td>总量</td>
<td>操作</td>
</tr>
<tr v-for="(c, index) in data" :key="index">
<td>{{ c.title }}</td>
<td>{{ c.price }}</td>
<td>{{ c.price * c.count }}</td>
<td>{{ c.count }}</td>
<td>
<button @click="reduce(index)">-</button>
<button @click="add(index)">+</button>
</td>
</tr>
<p>总价:{{ total }}元</p>
</table>
</div>
</template>
<script>
export default {
props: {
data: {
type: Array
}
},
computed: {
total() { //累加 数组的 reduce()
return this.data.reduce((sum, v) => {
return sum + v.price * v.count;
}, 0);
}
},
methods: {
add(i) { //子传父
this.$emit("addF", { index: i });
},
reduce(i) {
this.$emit("reduceF", { index: i });
}
}
};
</script>
<style scoped></style>