当在vue中定义一个子组件,从父组件给子组件传递数据可以通过在子经组件定义中通过props属性来传递数据过去:
<div id="box"> <cart :goods="goods"></cart> <span>总价:{{totalPrice}}元</span> </div> <script type="text/x-template" id="cart"> <table border="1px" width="90%"> <tr> <th>序号</th> <th>产品名称</th> <th>价格</th> <th>数量</th> </tr> <tr v-for="(item,key) in goods"> <td>{{key + 1}}</td> <td>{{item.goodsName}}</td> <td>{{item.price}}</td> <td> <input type="text" v-model="item.num" @blur="sum"> </td> </tr> </table> </script> <script type="text/javascript"> var cart = { props:['goods'], template:'#cart', }; var app = new Vue({ el:'#box', mounted(){ this.total(); }, methods:{ total(){ console.log('total'); this.totalPrice = 0; this.goods.forEach((v)=>{ this.totalPrice += v.num * v.price; }) } }, data:{ totalPrice:0, goods:[ {goodsName:'iphone7Plus',price:600,num:1}, {goodsName:'vip卡',price:200,num:1}, ] }, components:{cart} }); </script>
然后标签页中使用:goods来进行绑定数据,然后就可以在模板中使用数据了,效果如下:
如果在子组件中改变数量值时,如果修改总价,此时就牵涉到了从子组件发送事件到父组件,此时就得使用$emit函数进行触发:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script> <link href="https://cdn.bootcss.com/bootstrap/4.1.0/css/bootstrap.min.css" rel="stylesheet"> <script type="text/javascript" src="./node_modules/vue/dist/vue.js"></script> <script type="text/javascript" src="./node_modules/vue-resource/dist/vue-resource.js"></script> </head> <body> <div id="box"> <cart :goods="goods" @sum="total"></cart> <span>总价:{{totalPrice}}元</span> </div> <script type="text/x-template" id="cart"> <table border="1px" width="90%"> <tr> <th>序号</th> <th>产品名称</th> <th>价格</th> <th>数量</th> </tr> <tr v-for="(item,key) in goods"> <td>{{key + 1}}</td> <td>{{item.goodsName}}</td> <td>{{item.price}}</td> <td> <input type="text" v-model="item.num" @blur="sum"> </td> </tr> </table> </script> <script type="text/javascript"> var cart = { props:['goods'], template:'#cart', methods:{ sum(){ console.log('sum'); this.$emit('sum') } } }; var app = new Vue({ el:'#box', mounted(){ this.total(); }, methods:{ total(){ console.log('total'); this.totalPrice = 0; this.goods.forEach((v)=>{ this.totalPrice += v.num * v.price; }) } }, data:{ totalPrice:0, goods:[ {goodsName:'iphone7Plus',price:600,num:1}, {goodsName:'vip卡',price:200,num:1}, ] }, components:{cart} }); </script> </body> </html>