zoukankan      html  css  js  c++  java
  • 042——VUE中组件之子组件使用$on与$emit事件触发父组件实现购物车功能

    <!DOCTYPE html>
    <html lang="en">
    
    	<head>
    		<meta charset="UTF-8">
    		<title>组件之子组件使用$on与$emit事件触发父组件实现购物车功能</title>
    		<script src="vue.js"></script>
    	</head>
    
    	<body>
    		<div id="hdcms">
    			<hd-news :listdata="goods" @sum="total"></hd-news><!--@sum的作用是把父組件的事件綁定到子組件中-->
    			<h2>总价:{{totalPrice}}</h2>
    		</div>
    		<script typeof="text/x-template" id="hdNews">
    			<table border="2" bordercolor="black" cellspacing="0" cellpadding="20">
    				<tr>
    					<td>商品名称</td>
    					<td>价格</td>
    					<td>数量</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"><!--失去焦点之后触发子组件绑定的事件-->
    					</td>
    				</tr>
    			</table>
    		</script>
    		<script>
    			var hdNews = {
    				template: "#hdNews",
    				props: ['listdata'],//继承父组件的数据
    				methods: {
    					sums() {
    						this.$emit('sum');//@emit的作用就是子组件呼叫父组件的事件
    					}
    				}
    			};
    			new Vue({
    				el: "#hdcms",
    				components: {hdNews},
    				mounted() { //当vue执行完毕之后,去执行函数
    					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>
    

      

  • 相关阅读:
    【数量技术宅|金融数据分析系列分享】为什么中证500(IC)是最适合长期做多的指数
    异常控制流
    链接
    最小生成树的Prim算法(待修正版)
    最小生成树的Kruskal算法
    优先队列用法(转载)
    不相交集合的链表实现
    寻找通用汇点
    找零问题
    【Angular06】管道(类似vue的过滤器)、变更检测的工作原理
  • 原文地址:https://www.cnblogs.com/yiweiyihang/p/8203625.html
Copyright © 2011-2022 走看看