【Vue】Vue3父子组件相互调用示例

发布于:2024-04-14 ⋅ 阅读:(147) ⋅ 点赞:(0)

Tips:使用场景情况有很多,通常常见于页面表单赋值,表单属性页面回显。
页面给弹窗dialog表单赋值,通常情况为父传子;而表单提交后回传给页面数据,通常情况为子传父。

1. 父调子示例

1.1 父组件

<template>
	<button @click="demoClick ">触发子组件方法</button>
	<UpdateDlg ref="refupdate"></UpdateDlg>
</template>

<script setup lang="ts">
import { ref } from 'vue';
const refupdate= ref();

/**
 *  假设此处触发了点击事件:数据显示
 */
const demoClick = () => {
	const data = {...temp};
    refupdate.value.show(data);
};
</script>

<style scoped>
</style>

1.2 子组件

<template>
</template>

<script setup lang="ts">
/**
 *  数据显示
 * @param {*} data
 */
const show = (data) => {
	//此处会被调用,请补充内容
};
	
/**
 *  导出函数
 */
defineExpose({
  show
});
</script>

<style scoped>
</style>

2. 子调父示例

2.1 父组件

<template>
	<UpdateDlg ref="refupdate" @onsaved="refreshData"></UpdateDlg>	<!-- 主要关注refreshData就行了 -->
</template>

<script setup lang="ts">
import { ref } from 'vue';
const refupdate= ref();

/**
 *  数据显示
 */
const refreshData = () => {
    //此处会被调用,请补充内容
};
</script>

<style scoped>
</style>

2.2 子组件

<template>
</template>

<script setup lang="ts">
import { defineEmits } from 'vue';
const $emit = defineEmits(['onsaved']) //主要关注onsaved就行了

/**
 *  假设此处出发了点击事件:数据显示
 */
const demoClickSaved = () => {
	$emit('onsaved');
};
</script>

<style scoped>
</style>