方法一:传统的typescript
<!-- ParentComponent.vue -->
<template>
<div>
<h2>Parent Component</h2>
<button @click="showDialog = true">Show Dialog</button>
<ChildComponent :visible="showDialog" @close="showDialog = false" />
</div>
</template>
<script lang="ts">
import { defineComponent, ref } from 'vue';
import ChildComponent from './ChildComponent.vue';
export default defineComponent({
name: 'ParentComponent',
components: { ChildComponent },
setup() {
const showDialog = ref(false);
return {
showDialog,
};
},
});
</script>
<!-- ChildComponent.vue -->
<template>
<n-dialog v-model:value="visible" @close="onClose">
<div>Child Component</div>
</n-dialog>
</template>
<script lang="ts">
import { defineComponent, PropType } from 'vue';
import { NDialog } from 'naive-ui';
export default defineComponent({
name: 'ChildComponent',
components: { NDialog },
props: {
visible: {
type: Boolean as PropType<boolean>,
required: true,
},
},
emits: ['close'],
setup(props, { emit }) {
const onClose = () => {
emit('close');
};
return {
onClose,
};
},
});
</script>
方法二:使用了setup的typescript
<!-- ChildComponent.vue -->
<script lang="ts">
// 导出组件
export default {
name: 'Profile'
}
</script>
<script lang="ts" setup>
// 导入组件
import { NModal } from 'naive-ui'
import {reactive} from 'vue'
// 定义接受的参数,父组件想下传递visible
const props = defineProps(['visible'])
// 定义回调方法(要调用父组件的close方法)
const emit = defineEmits(['close'])
// 定义子组件中的数据模型
const model = reactive({
visible: false,
})
// 将从父组件接受的参数传递给子组件模型赋值
const handleInit = () => {
model.visible = props.visible
}
// 定义子组件的方法,该方法调用父组件的close方法,修改父组件的visible参数
const handleClose = () => {
emit('close')
}
// 调用初始化参数方法
handleInit()
</script>
<template>
<NModal
v-model:show="model.visible" // 使用visible控制显示和隐藏
:mask-closable="false"
title='Profile'
preset="dialog"
@close="handleClose" // 关闭时调用handleClose方法
>
你好你好
</NModal>
</template>
<script lang="ts" setup>
import { ref } from 'vue';
import Profile from '@/components/common/Profile/index.vue'
const showProfile = ref(false)
</script>
<template>
<div>
<h2>Parent Component</h2>
<button @click="showProfile = true">Show Dialog</button>
<Profile v-if="showProfile" v-model:visible="showProfile" @close="showProfile = false" />
</div>
</template>
简单来说就是父组件通过插值props向下传递参数(showProfile实参,visible形参),控制子组件的显示和隐藏。(但是这个visible不能直接使用,将其传递给了子组件中的参数visible)
子组件通过调用emit父组件的方法(close方法),修改父组件的参数(show)