以下将依据理论业务场景进行剖析,梳理vue3.0+ts我的项目中的父子组件通信。

一、父组件

咱们假设咱们有一个这样的父组件Parent.vue,在咱们点击编辑按钮之后弹出咱们的子组件弹窗Model.vue。在应用子组件时,咱们应用了双向绑定visible、参数rowInfo、以及更新办法getSystemList,接下来咱们看下在子组件中咱们怎么做来放弃与父组件的通信。

<template>  <a class="ant-btn-link" @click="edit(record)">编辑</a>  <system-modal v-model:visible="showAdd" :rowInfo="rowInfo"    @getSystemList="getSystemList"></system-modal></template><script setup lang="ts">import { ref, onMounted } from 'vue'import SystemModal from './modal.vue'const showAdd = ref(false)type rowInfoKeys =  | 'isOther'  | 'appOnlyId'  | 'backAddress'  | 'connectGateway'  | 'secretGateway'  | 'zeroTrustGateway'type rowInfoType = Partial<Record<rowInfoKeys, any>>const rowInfo: { value: rowInfoType } = ref({  appOnlyId: '',  backAddress: '',  connectGateway: [],  secretGateway: false,  zeroTrustGateway: false,})const edit = (row: any): void => {  rowInfo.value = { ...row }  showAdd.value = true}//数据更新const getSystemList = () => {    //在这里编写你的数据更新代码}</script>

咱们的父组件大略长这个样子:

二、子组件

首先咱们先来接管到来自父组件的参数visible、rowInfo并保留至对象props中,那么后续咱们就能够在子组件中应用到props中的数据了。接下来咱们定义(defineEmits)更新事件:
1、'update:visible' 在弹窗敞开时,同步告知父组件更新visible的值。
2、'getSystemList' 当咱们在弹窗内操作了form表单筹备保留数据,点击确认时,将告知父组件进行更新数据。

<template>  <a-modal title="编辑" v-model:visible="visible" @cancel="close" :maskClosable="false">    <!-- v-model="showAdd" -->    <template #footer>      <div class="textAlignCenter">        <a-button type="dashed" size="mini" @click="close">勾销</a-button>        <a-button type="primary" size="mini" @click="confirmSave">          确认        </a-button>      </div>    </template>    <div>      <a-form ref="formRef" :labelCol="{ style: { width: '150px' } }" :model="props.rowInfo" required        autocomplete="off">        <a-form-item label="名称:">          {{props.rowInfo.appName}}        </a-form-item>        <--这里可能还有别的表单元素(你的业务场景)-->      </a-form>    </div>  </a-modal></template><script lang="ts" setup>import { message, Modal } from 'ant-design-vue'import { ref, onMounted, Ref } from 'vue'interface Props {  visible?: boolean  rowInfo?: any}const props = withDefaults(defineProps<Props>(), {  visible: false,  rowInfo: {},})const emit = defineEmits(['update:visible', 'getSystemList'])const close = function () {  emit('update:visible', false)  selectOpen.value = false}const confirmSave = () => {    //这里可能会有很多校验,通过之后告知父组件更新数据。    emit('getSystemList')}</script>

咱们的子组件大略长这样子:

以上是一个简略的父子通信的示例,心愿对你有帮忙。