关于父类组件和子类组件的互相传值

第一步:子类向父类传值

在java中父类是可以将值传给子类的,但是却不能从子类拿到值,同理子类是可以将父类的值拿到手,但是却不能将自己的值传给父类

而在vue中,子类和父类之间是不允许传值的但是,我们可以利用关联和引用来让他们之间建立起一些联系

子类向父类传值要使用$emit方法

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>子类向父类传值</title>
	<script src="https://cdn.bootcss.com/vue/2.5.14/vue.min.js"></script>
	<script src="https://cdn.bootcss.com/axios/0.17.1/axios.min.js"></script>
</head>
<body>
	<div id="box">
		<parent1></parent1>
	</div>
	<!-- 父 -->
	<template id="p">
		<h1>{{parentmsg}}<child1 @chuandi="shouji"></child1></h1>
	</template>

	<!-- 子 -->
	<template id="c">
		<div>
		<input type="text" v-model="childmsg">
		<button @click="fanhui">点击就将这个input标签的值传递给父类的方法,并改变父类标签的内容</button>
		</div>
	</template>
	<script>
		let vm = new Vue({
			el:"#box",
			data:{
				msg:"ds",
			},
			components:{
				"parent1":{
					template:"#p",
					data:function(){
						return{
							parentmsg:"父类的内容",
						}
					},
					methods:{
						shouji:function(value){
							alert(value);
							this.parentmsg=value;
						}
					},
					components:{
						"child1":{
							template:"#c",
							data:function(){
								return{
									childmsg:"自乐",
								}
							},
							methods:{
								fanhui:function(){
									this.$emit("chuandi",this.childmsg);
								}
							}
						}
					}
				}
			}
		})
	</script>
</body>
</html>

为了方便理解,我们就从父类开始分析他们之间的联系

1首先父类定义了一个用来接收子类准备返回值的方法——shouji()该方法触发按钮和事件,它只是等待子类使用emit方法来触发它

2然后我们给该方法取了个别名绑定到一个叫做@chaundi的方法名上,该不处理是在父类组件中引用子类组件的时候传递给子类组件的

3然后子类组件中有一个方法叫做fanhui,该方法是由button按钮触发的,但我们点击按钮的时候,该方法体内部的

this.$emit("chuandi",this.childmsg);会将该子组件的childmsg传递给别名为chuandi的父类的shouji方法,然后父类shouji方法的value参数就会接收到childmsg的值,父组件就能使用了

步骤不多:一共就是父类监听,然后取个别名传给子组件,子组件使用emit调用别名,并返回值给父类监听方法

第二步:父组件向子组件传递值

这种就比上一种还要简单点

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>父向子传值</title>
	<script src="https://cdn.bootcss.com/vue/2.5.14/vue.min.js"></script>
	<script src="https://cdn.bootcss.com/axios/0.17.1/axios.min.js"></script>
</head>
<body>
	<div id="box">
		<parent1 :mess="msg"></parent1>
	</div>

	<!-- 父框架 -->
	<template id="p">
		<h1>父类文字内容<child1 :message="mess"></child1></h1>
	</template>

	<!-- 子类文字内容 -->
	<template id="c">
		<h1>子类文字内容{{message}}</h1>
	</template>

	<script>
		let vm = new Vue({
			el:'#box',
			data:{
				msg:"kn"
			},
			components:{
				"parent1":{
					template:"#p",
					props:["mess"],
					data:function(){
						return{
							msg1:"父类传给子类的遗产",
						}
					},
					/*父类里面嵌入子*/
					components:{
						"child1":{
							template:"#c",
							props:['message'],
						}
					}
				}
			}
		})
	</script>
</body>
</html>

这里我们所做的就是将最外围的vue的msg值传递到最里层的子组件中去

我们第一步将值从vue传递到父组件,在div#box中引用父组件的时候,就将msg去个别名赋给:mess

然后父组件定义props:【“mess”】接收了该值,然后在父组件的template中引用子组件的标签的时候将mess取个别名

:message=”mess“,同理子啊子组件的props:【”message“】也定义了一番,然后就可以在子组件的template中直接使用{{message}}来接收来自父组件的值了。

猜你喜欢

转载自blog.csdn.net/jinqianwang/article/details/82859525