Vue中父子组件传值的方式

本文详细介绍了Vue.js中父组件与子组件之间的数据传递方法,包括如何通过props将数据从父组件传递到子组件,以及如何利用ref在父组件中访问子组件的属性和方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

父组件向子组件传值

  1. 父组件调用子组件时,在标签上绑定动态属性
<template>
    <div id='parent'>
        <v-child :title='title' :run='run'></v-child>
    </div>
</template>

<script>
import Child from './Child.vue';
	
export default{
	data(){
		return{
			msg:'',
			title:'我是Parent组件的值'
		}
	},
	methods:{
		run(data){
			alert('我是Parent组件的run方法 --' + data);
		}
	},
	components:{
		'v-child': Child
	}
}
</script>

     2.子组件通过props方式接受父组件传来的值

<template>
	<div id="child">
	    <p>{{title}}</p>
        <button @click="run(123)">点击查看父组件的方法</button>
	</div>
</template>

<script>
  export default{
  	data(){
  		return{
  			
  		}
  	},
  	props:{
  		title: String,  //在props中可以对传来的数据进行类型验证
  		run: Function,
  	}
  }
</script>

子组件向父组件传值

      1. 调用子组件时定义一个ref,如下
          <v-child ref='child'><v-child>

      2. 在父组件里通过以下方式接收子组件的值
           this.$refs.child.属性
           this.$refs.child.方法

<template>
	<div id="parent">
		<v-child ref='child'></v-child>
		<button @click='getChildData()'>获取子组件的数据</button>
		<br />
		<button @click='getChildFunction()'>获取子组件的方法</button>
	</div>
</template>

<script>
	
import Child from './Child.vue';
	
  export default{
  	data(){
  		return{
  			msg: ''
  		}
  	},
  	methods:{
  		getChildData(){
  			alert(this.$refs.child.msg); //获取子组件的msg
  		},
  		getChildFunction(){
  			this.$refs.child.run();  //获取子组件的run方法
  		}
  	},
  	components:{
  		'v-child':Child
  	}
  }
</script>

这只是基础的父子组件传值方式,其它方式会在后面进行补充

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值