vue3父子组件相互调用方法

126 阅读1分钟

一、父组件调用子组件的方法

子组件需要通过defineExpose对外暴露方法和属性;给父组件通过ref去调用; 子组件

<template>
  <div>子组件</div>
</template>

<script lang="ts" setup>
  import { ref, nextTick,  } from 'vue';
  const emit = defineEmits(['register', 'success']);

  function submitCallback() {
    handleCancel();
    emit('success');
  }

  defineExpose({
    disableSubmit,
  });
</script>

<style>
</style>

父组件

<template>
   <button @click="getChild">触发子组件方法</button>
  	<!-- 一:定义 ref -->
   <Subclass ref="childRef"></Subclass>
</template>

<script lang="ts" setup>
  import { ref } from 'vue';
	import Subclass from '../../components/subclass.vue';
  import { ref, nextTick,  } from 'vue';
  const childRef=ref<any>()
    
  const getChild=()=> {
    childRef.value.submitCallback()
  }

</script>

<style>
</style>

二、子组件调用父组件的方法

子组件

<template>
  <div>子组件</div>
</template>

<script lang="ts" setup>
  import { ref, nextTick,  } from 'vue';
  const emit = defineEmits(['register', 'success']);

  const submitCallback=()=> {
    emit('success','调用父组件的方法');
  }

  defineExpose({
    disableSubmit,
  });
</script>

<style>
</style>

父组件

<template>
   <button @click="getChild">触发子组件方法</button>
  	<!-- 一:定义 ref -->
   <Subclass ref="childRef" @handSuccess="success"></Subclass>
</template>

<script lang="ts" setup>
  import { ref } from 'vue';
	import Subclass from '../../components/subclass.vue';
  import { ref, nextTick,  } from 'vue';
  const childRef=ref<any>()
    
  const getChild=()=> {
    childRef.value.submitCallback()
  }
  const handSuccess=(argument)=>{
    console.log('=====>接收子组件的参数',argument)
  }

</script>

<style>
</style>