Vue父子组件传值(子传父)

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
		<script src="https://cdn.bootcss.com/vue/2.5.16/vue.js"></script>
    <script src="https://cdn.bootcss.com/axios/0.17.0/axios.min.js"></script>
</head>
<body>
	<!-- 由于子类与父类都不能直接获取双方的属性,所以子传父也称为逆传值 -->
	<!-- 思路:通过子类模板的方法引用$emit,把值传给父类,父类引用子组件时,即可获得子类传的值 -->
	<div id="box">
		<parent></parent>
	</div>

	<!-- 父类组件 -->
	<template id="par">
		<div>
			<h1>父类组件获得值:{{famsg}}</h1>
			<!-- 在父类模板中的子类组件用$emit设置的方法,此方法不能有括号!!!否则报错 -->
			<child v-on:dian-ji-chuan-zhi="getData"></child>
		</div>
	</template>

	<!-- 子类组件 -->
	<template id="ch">
		<div>
			<!-- 在子类的模板里定义点击方法,用于触发传值方法,也可以在钩子函数mounted里触发方法 -->
			<h1 @click="chuan">子类组件内的值(点击事件):{{chmsg}}</h1>
		</div>
	</template>
	<script type="text/javascript">
		var vm=new Vue({
			el:"#box",
			components:{
				/*定义父类组件*/
				"parent":{
					template:"#par",
					data:function(){
						return {famsg:""}
					},
					methods:{
						/*参数就是子类返回的数据,名字可以自定义*/
						getData(var3){
							this.famsg=var3;
						}
					},
					/*定义子类组件*/
					components:{
						"child":{
							template:"#ch",
							/*定义子类的数据*/
							data:function(){
								return {chmsg:"吴师傅"}
							},
							methods:{
								chuan(){
									/*用emit自定义名字最好别用大写,大写需要使用dian-ji-chuan-zhi,对应父类模板的子类组件*/
									this.$emit("dian-ji-chuan-zhi",this.chmsg);
								}
							}
						}//child
					}//components
				}//parnet
			}
		});
	</script>
</body>
</html>

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值