Vue中简单的父子组件传值

一、父组件通过props给子组件传值

  1. 在父组件的子组件标签上绑定一个属性,挂载要传输的变量。
  2. props就是父组件给子组件标签上定义的属性,用来接收父组件传递的数据,props的值可以是字符串数组,也可以是各自的名称和类型,用法和data中的数据用法一样,在子组件中只能使用该值,不能修改。
  3. 在子组件中通过props来接收数据,props可以是数组也可以是对象,接受的数据可以直接使用props:[“属性名”]或 props:{属性名:数据类型}
 如:   1. props:["message"]
 		2. props:{
 			message:{
 				type: String,
 				default: "";
 			},
 		}

父组件通过props给子组件传值的示例如下:

//父组件
<template>
	<div>
		<son :height='height'></son>	//3. 页面使用子组件 并将height值传递给子组件
	</div>
</template>

<script>
import son from "./son.vue";//  1. 导入子组件
export default {
	components:{ son },     //  2. 注册子组件
	data(){
		return {
			height: "180----父组件传给子组件的值",
		}
	}
}
</script>
//子组件
<template>
	<div>
		{{height}}  // 2. 使用父组件传过来的数据
	</div>
</template>

<script>
export default {
	props:{
		height:[],  //  1. 子组件通过props接收父组件传过来的数据
	}
	data(){
		return {
		}
	}
}
</script>

二、子组件通过触发$emit事件给父组件传值

  1. 在父组件的子组件标签上自定义一个事件,然后调用需要的方法
  2. 在子组件的方法中通过this.$emit(“事件”)来触发在父组件中定义的事件,数据是以参数的形式进行传递的。
  3. $emit的第一个参数为自定义的事件,第二个参数为要传递给父组件的值,父组件在子组件的标签上绑定自定义事件来接收子组件传递的数据。

子组件通过触发$emit事件给父组件传值的示例如下:

//子组件
<template>
	<div>
		<button @click="clickMethod"></button>
	</div>
</template>

<script>
export default {
	data(){
		return {
			message:"给父组件传递的数据",
			height:"180-----传递的数据"
		}
	},
	methods:{
		clickMethod(){
			.....
			// 1. 通过$emit将数据传递给父组件。
			// 2. $emit的第一个参数为自定义的事件,第二个参数为要传递给父组件的值,
			this.$emit("passParam",{this.message,this.height})  
		}
	}
}
</script>
//父组件
<template>
	<div>
		<son 
			:height='height'
			@passParam="getParam"  //3. 页面使用子组件 通过子组件自定义的passParam事件,
		></son>	                   //  用getParam方法处理子组件传递过来的数据
	</div>
</template>

<script>
import son from "./son.vue";//  1. 导入子组件
export default {
	components:{ son },     //  2. 注册子组件
	data(){
		return {
			height: "180----父组件传给子组件的值",
			sonParam:'',  //用于保存数据
		}
	},
	methods:{
		getParam(param){  // 4. 用getParam方法处理子组件传递过来的数据
			this.sonParam=param;
		}
	}
}
</script>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值