vue2 vue3 父子组件相互调用方法

本文详细介绍了在Vue3和Vue2中如何实现父子组件之间的方法调用。在Vue3中,使用`ref`和`defineExpose`来实现,而在Vue2中,通过`$refs`和`$parent`属性进行通信。示例代码展示了在模板、脚本和样式中的具体实现细节,帮助开发者理解这两种不同版本Vue中的父子组件交互机制。
摘要由CSDN通过智能技术生成

vue3 父子组件相互调用方法

父组件

<script setup lang="ts">
import HelloWorld from './components/HelloWorld.vue'
import { ref } from 'vue'


// 接收子组件的方法 在子组件中用ref获取元素
const helloWorldRef = ref()
const fromSon = () =>{
  console.log(helloWorldRef.value.toFather()); // 子组件的值
}


// 自定义方法
const openPopup = ()=>{
  console.log('父组件的值');
}
</script>

<template>
<div>
  <HelloWorld ref="helloWorldRef" @toSon="openPopup" />
  <button @click="fromSon">获取子组件方法</button>
</div>
  
</template>

<style>
</style>

子组件

<script setup lang="ts">



// 导入父组件方法用emit接收
const emit = defineEmits(['toSon'])
const fromFather = ()=>{
    emit('toSon')
}


// 导出子组件的方法
const son:String = '子组件的值'
const toFather = () =>{
    return son
}
 defineExpose({toFather})
</script>

<template>
 <div>
  HelloWorld
  <button @click="fromFather">调用父组件方法</button>
 </div>
</template>

<style scoped lang="scss">
</style>

vue2 父子组件相互调用方法

父组件

<template>
  <div class="home">
    <HelloWorld ref="HelloWorld"/>
    <button @click="fromFather">获取子组件方法</button>
  </div>
</template>

<script>
// @ is an alias to /src
import HelloWorld from '@/components/HelloWorld.vue'

export default {
  name: 'HomeView',
  components: {
    HelloWorld
  },
  methods:{
    //父组件方法
    toSon(){
      console.log('父组件的值')
    },
    fromFather(){
      // 调用子组件方法
      this.$refs.HelloWorld.toFather()
    }
  }
}
</script>

子组件

<template>
  <div class="hello">
    HelloWorld
    <button @click="fromFather">获取父组件方法</button>
  </div>
</template>

<script>
export default {
  name: 'HelloWorld',
  methods:{
    // 调用父组件方法
    fromFather(){
      this.$parent.toSon()
    },
    // 子组件方法
    toFather(){
      console.log('子组件的值')
    }
}

}
</script>

<style scoped lang="less">
</style>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值