父组件中语法与Vue2一样,如:
<template>
<el-form ref="formRef" :model="formData" :rules="rules" label-width="120px">
<el-row>
<el-col :span="12">
<el-form-item label="表名称" prop="tableName">
<el-input placeholder="请输入仓库名称" v-model="formData.tableName" />
el-form-item>
el-col>
el-row>
el-form>
<UploadBatch
ref="uploadBatchRef"
:uploadDialogVisible="uploadBatchVisible"
:fill-id="fillId"
@set-visible="setVisible"
/>
template>
子组件UploadBatch
在defineProps
内接收:
<script setup lang="ts" name="UploadBatch">
const props = defineProps({
uploadDialogVisible: { // Boolean类型
type: Boolean,
default: false
},
fillId: { // Number类型
type: Number,
default: null
},
boxNo: { // String类型
type: String,
default: ''
},
// 以下为其他类型演示!!!
value: String,
processId: String,
processName: String,
formId: Number,
translations: {
type: Object,
default: () => {}
},
additionalModel: [Object, Array],
moddleExtension: {
type: Object,
default: () => {}
},
prefix: {
type: String,
default: 'camunda'
},
events: {
type: Array,
default: () => ['element.click']
},
headerButtonSize: {
type: String,
default: 'small',
validator: (value: string) => ['default', 'medium', 'small', 'mini'].indexOf(value) !== -1
}
})
</script>
子组件中使用props的属性,可以用toRef和toRefs,取出来的属性还是响应式的,如:
const { fillId, uploadDialogVisible, boxNo } = toRefs(props) // 取出所有响应式属性
const fillId = toRef(props, 'fillId') // 或者只取单个属性
console.log(fillId.value) // 要用.value取真正的值,否则只是个响应式对象!但在template模板中无需加.value
注意:严格遵循单向数据流,子组件不要修改父组件传过来的属性值!可以通过emit发给父组件一个通知让父组件自己去修改这个属性值!
父组件中语法与Vue2一样,如:
<UploadBatch
ref="uploadBatchRef"
:uploadDialogVisible="uploadBatchVisible"
:fill-id="fillId"
@set-visible="setVisible"
@reload-data="reloadData"
/>
<script setup lang="ts">
const setVisible = (value) => {
uploadBatchVisible.value = value
uploadPhotoVisible.value = value
}
const reloadData = (value) => {
reviewAuditStatus.value = String(value.reviewAuditStatus)
reasonForFailure.value = value.reasonForFailure
}
script>
子组件中定义defineEmits
:
// 定义
const emit = defineEmits(['setVisible', 'reflsheData'])
// 然后通过emit调用父组件setVisible和reloadData方法
const close = () => {
emit('setVisible', false)
emit('reloadData', { reviewAuditStatus: flag.value, reasonForFailure: reasonForFailure.value })
}
在子组件中使用Vue3
的语法糖defineExpose
:
<script setup lang="ts">
const initData = async (detailId, type) => {
console.log(detailId)
console.log(type)
console.log('初始化数据...')
}
defineExpose({
xGridRef: xGrid,
info: props.info
initData
})
</script>
父组件中:
<template>
<UploadBatch
ref="uploadBatchRef"
:uploadDialogVisible="uploadBatchVisible"
:fill-id="fillId"
@set-visible="setVisible"
/>
template>
<script setup lang="ts">
const uploadBatchRef = ref()
uploadBatchRef.value?.initData(detailId.value, 1)
script>