子组件使用$emit事件触发父组件实现购物车功能
实现类似淘宝,京东的购物车功能,源码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script src="vue.js"></script>
<title>Title</title>
</head>
<body>
<div id="app">
<v-header :list="goods" @sum="total"></v-header>
总价格:{{totalprice}}元
</div>
<script type="text/x-template" id="header">
<table width="100%" border="1">
<tr>
<th>商品名称</th>
<th>商品单价</th>
<th>商品数量</th>
</tr>
<tr v-for="v in list">
<td>{{v.name}}</td>
<td>{{v.price}}</td>
<td><input type="text" v-model="v.num" @blur="sum"></td>
</tr>
</table>
</script>
<script>
var vHeader={
vHeader,
template:'#header',
data(){
return{
}
},
props:[
'list',
],
methods:{
sum(){
this.$emit('sum')
}
}
};
new Vue({
el:'#app',
data:{
goods:[
{name:'phone1',price:'200',num:'3'},
{name:'phone2',price:'200',num:'3'},
{name:'phone3',price:'200',num:'3'},
],
totalprice:0,
},
components:{
vHeader,
},
mounted(){
this.total()
},
methods:{
total(){
this.totalprice=0;
this.goods.forEach((v)=>{
this.totalprice+=v.price*v.num;
})
}
}
})
</script>
</body>
</html>
第一步,在主组件下创建一个组件;
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script src="vue.js"></script>
<title>Title</title>
</head>
<body>
<div id="app">
<v-header></v-header>
</div>
</body>
<script>
var vHeader={vHeader,
template:'#header',
}
new Vue({
el:'#app',
data:{
components:{
vHeader,
},
}
})
</script>
</html>
这时,在预览的时候是没有问题的,下边我们就要写templates:’#header’,的内容了。
如下:
<script type="text/x-template" id="header">
<table width="100%" border="1">
<tr>
<th>商品名称</th>
<th>商品单价</th>
<th>商品数量</th>
</tr>
</table>
<script>
第二步:在添加商品属性:
<script type="text/x-template" id="header">
<table width="100%" border="1">
<tr>
<th>商品名称</th>
<th>商品单价</th>
<th>商品数量</th>
</tr>
<tr v-for="v in list">
<td>{{v.name}}</td>
<td>{{v.price}}</td>
<td><input type="text" v-model="v.num"></td>
</tr>
</table>
</script>
<script>
var vHeader={
vHeader,
template:'#header',
props:[
'list',
],
};
new Vue({
el:'#app',
data:{
goods:[
{name:'phone1',price:'200',num:'3'},
{name:'phone2',price:'200',num:'3'},
{name:'phone3',price:'200',num:'3'},
]
},
components:{
vHeader,
},
})
</script>
第三步:添加总价
<div id="app">
<v-header :list="goods" @sum="total"></v-header>
总价格:{{totalprice}}元
</div>
<td><input type="text" v-model="v.num" @blur="sum"></td>
<!--在子组件中添加方法:--!>
methods:{
sum(){
this.$emit('sum')
}
}
<!--在主组件中计算价格:--!>
data:{
goods:[
{name:'phone1',price:'200',num:'3'},
{name:'phone2',price:'200',num:'3'},
{name:'phone3',price:'200',num:'3'},
],
totalprice:0,
},
components:{
vHeader,
},
mounted(){
this.total()
},
methods:{
total(){
this.totalprice=0;
this.goods.forEach((v)=>{
this.totalprice+=v.price*v.num;
})
}
}