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

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>


版权声明:本文为weixin_47619284原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。