042——VUE中组件之子组件使用$on与$emit事件触发父组件实现购物车功能
生活随笔
收集整理的這篇文章主要介紹了
042——VUE中组件之子组件使用$on与$emit事件触发父组件实现购物车功能
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8"><title>組件之子組件使用$on與$emit事件觸發(fā)父組件實(shí)現(xiàn)購物車功能</title><script src="vue.js"></script></head><body><div id="hdcms"><hd-news :listdata="goods" @sum="total"></hd-news><!--@sum的作用是把父組件的事件綁定到子組件中--><h2>總價(jià):{{totalPrice}}</h2></div><script typeof="text/x-template" id="hdNews"><table border="2" bordercolor="black" cellspacing="0" cellpadding="20"><tr><td>商品名稱</td><td>價(jià)格</td><td>數(shù)量</td></tr><tr v-for="(v,k) in listdata"><td>{{v.name}}</td><td>{{v.price}}</td><td><input type="text" v-model="v.num" @blur="sums"><!--失去焦點(diǎn)之后觸發(fā)子組件綁定的事件--></td></tr></table></script><script>var hdNews = {template: "#hdNews",props: ['listdata'],//繼承父組件的數(shù)據(jù)methods: {sums() {this.$emit('sum');//@emit的作用就是子組件呼叫父組件的事件}}};new Vue({el: "#hdcms",components: {hdNews},mounted() { //當(dāng)vue執(zhí)行完畢之后,去執(zhí)行函數(shù)this.total();},data: {totalPrice: 0,goods: [{name: '蘋果X',price: 200,num: 1},{name: '華為P10',price: 100,num: 1},{name: '小米6',price: 50,num: 1},]},methods: {total() {this.totalPrice = 0;this.goods.forEach((v) => {this.totalPrice += v.num * v.price;});}}});</script></body></html>
創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎勵來咯,堅(jiān)持創(chuàng)作打卡瓜分現(xiàn)金大獎
總結(jié)
以上是生活随笔為你收集整理的042——VUE中组件之子组件使用$on与$emit事件触发父组件实现购物车功能的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 可编辑选择、删除条目的ListView
- 下一篇: window tool