【父子组件传值】Vue子父组件传值的三种方法

文章详细介绍了在Vue.js中如何进行父子组件之间的通信。通过props,父组件能将数据传递给子组件;子组件则可以使用this.$emit触发自定义事件,将信息回传给父组件。此外,使用refs可以直接访问子组件实例,调用其数据和方法。

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

父组件向子组件传值: props-父组件给子组件传输数据和验证

1.父组件的代码示例

<template>
<div>父组件</div>
// 引用子组件
<Dialog :fatherData="fatherData"></Dialog>
</template>

<script>
// 导入子组件
import Dialog from '@/components/Dialog.vue'

export default {
  name: 'HomeView',
  components: { Dialog },
  data () {
    return {
      fatherData: '父组件的值',
    }
  }
}
</script>

2.子组件的代码示例

<template>
  <div>
    <div>子组件</div>
    <div>
    //展示父组件数据
      {{fatherData}}
    </div>
  </div>
</template>
<script>
export default {
  data () {
    return {
      childrenData: '子组件自己的数据'
    }
  },
  //props的基本用法是父组件给子组件传输数据和验证
  props: {
  //父组件数据
    fatherData: {
      type: String
    }
  }
}
</script>

子组件向父组件传值:this.$emit()-子组件可以使用 $emit,让父组件监听到自定义事件

1.父组件的代码示例

<template>
<div>父组件</div>
// 引用子组件
<Dialog  @tranferData="tranferData"></Dialog>
//展示子组件的值
<div>{{ receiveData }}</div>
</template>

<script>
// 导入子组件
import Dialog from '@/components/Dialog.vue'

export default {
  name: 'HomeView',
  components: { Dialog },
  data () {
    return {
      fatherData: '父组件的值',
      receiveData:''
    }
  },
  methods: {
  //接收子组件传过来的数据
  tranferData(val){
  	console.log('子组件向父组件传过来的值:',val)
  	this.receiveData = val
  }
  }
}
</script>

2.子组件的代码示例

<template>
  <div>
    <div>子组件</div>
    <el-button @click="tranfer">子向父传值</el-button>
  </div>
</template>
<script>
export default {
  data () {
    return {
      childrenData: '子组件的值'
    }
  }
  },
  methods:{
  	tranfer(){
  	this.$emit('tranferData',this.childrenData)
  	}
  }
}
</script>

通过 r e f s 调用子组件的值 − 用 t h i s . refs调用子组件的值-用this. refs调用子组件的值this.refs 获取到的是组件实例,可以使用组件的所有方法

1.父组件的代码示例

<template>
<div>父组件</div>
// 引用子组件
<Dialog ref='dialogData'></Dialog>
<div>通过refs拿到子组件的值</div>
<el-button @click="toGet">refs拿到子组件的值</el-button>
</template>

<script>
// 导入子组件
import Dialog from '@/components/Dialog.vue'

export default {
  name: 'HomeView',
  components: { Dialog },
  data () {
    return {
      fatherData: '父组件的值',
    }
  },
  methods:{
  toGet(){
  	 // 通过refs调用子组件的值(childrenData)
    	const data = this.$refs.dialogData.childrenData
     	alert(data)
     //  通过refs调用子组件的值(childrenWay())
     	const way = this.$refs.dialogData.childrenWay()
     	alert(way)
  }
  }
}
</script>

2.子组件的代码示例

<template>
  <div>
    <div>子组件</div>
  </div>
</template>
<script>
export default {
  data () {
    return {
      childrenData: '子组件自己的数据'
    }
  },
  methods:{
  childrenWay(){
  	alert('父组件调用子组件的方法')
  }
  }
}
</script>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值