效果图
?
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>使用组件实现购物车事件</title>
<script src="../js/vue.js"></script>
</head>
<body>
<div id="app">
<div v-html="msg"></div>
<coma @lb="abb"></coma>
<ul>
<li v-for="(item,index) in list ">{{item.phone}} {{item.price}} {{item.num}}</li>
</ul>
</div>
</body>
<script type="text/javascript">
let coma =({
template: "<div>" +
"<h3>{{liebiao[0]}}</h3>" +
"<ul>" +
"<li v-for='(item,index) in abb ':key='item.id'>{{item.id}}、{{item.phone}} <button @click='btn(index)'>添加</button></li>" +
"</ul>" +
"<h3>{{liebiao[1]}}</h3>" +
"</div>",
data() {
return {
liebiao: ['产品列表', '我的购物车'],
abb: [{
id: 1,
phone: "华为手机",
price: 2000,
num: 1
},
{
id: 2,
phone: "锤子手机",
price: 2300,
num: 2
}, {
id: 3,
phone: "小米手机",
price: 2500,
num: 1
}
]
}
},
methods:{
btn(index) {
this.$emit("lb", this.abb[index])
}
}
})
new Vue({
el: "#app",
data: {
msg: "<h1>使用组件实现购物车</h1>",
list: []
},
methods: {
abb(data){
for (let i = 0; i < this.list.length; i++) {
if(this.list[i].phone==data.phone){
this.list[i].num++
return
}
}
this.list.push(data)
}
},
components: {
coma
},
})
</script>
</html>
|