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>

猜你喜欢

转载自blog.csdn.net/chijiajing/article/details/82859542
今日推荐