vue中要做到父子级之间的双向响应式数据传输,主要使用到 props, v-model, toRefs( props ), emits, updata:formData 等;本文章中使用 auto-import 插件省略了一些组件或 api 的引入,UI 组件为 AntD-vue 。 内容仅供参考!内容仅供参考!内容仅供参考!
1、使用 props 和 watch 的单向响应式数据
父级组件 fatherVue :
<template>
// fatherVue
<div>
<child-vue :form-data = "faToSonData">
</div>
</template>
<script lang="ts" setup>
import childVue from './childVue.vue';
const faToSonData = ref<any>{
name: 'kujo jotaro',
age: 18,
isStand: 'yes'
}
</script>
子集组件 childVue :
<template>
// childVue
<div>
<a-form :model="formDataSon" :label-col="{ style: { width: '120px' } }" ref="baseFormRef">
<a-form-item label="名字" name="name" >
<a-input v-model:value.trim="formDataSon.name" :maxlength="256" />
</a-form-item>
<a-form-item label="年龄" name="age" >
<a-input-number v-model:value="formDataSon.age" :min="1" :max="150" :precision="0" />
</a-form-item>
<a-form-item label="是否替身" name="isStand" >
<a-switch v-model:checked="formDataSon.isStand" unCheckedValue="no" checkedValue="yes" />
</a-form-item>
</a-form>
</div>
</template>
<script lang="ts" setup>
import {
ref, watch, nextTick } from 'vue';
import type {
FormInstance } from 'ant-design-vue';
const props = defineProps<{
formData: {
type: any,
required: true,
default:{
}
}
}>();
const formDataSon = ref