文章目录
- 父组件
- 1、@update和 : 拆开使用
- 2、computed 计算属性方法
- 3、defineModel (3.4+) 官方推荐
- 4、TS泛型用法(3.3+)
父组件
<template>
<div>
<button @click="dialogVisible = !dialogVisible">打开/关闭</button>
<ModalComp v-model="dialogVisible" v-if="dialogVisible" />
</div>
</template>
<script setup>
import ModalComp from './components/ModalComp.vue'
const dialogVisible = ref(false)
</script>
1、@update和 : 拆开使用
<template>
<el-dialog
:modelValue="modelValue"
@update:modelValue="$emit('update:modelValue', false)"
title="Tips"
width="800"
draggable
>
哈咯啊
</el-dialog>
</template>
<script setup>
defineProps({
modelValue: {
type: Boolean,
default: false
}
})
</script>
2、computed 计算属性方法
<template>
<el-dialog
v-model="dialogVisible"
title="Tips"
width="800"
draggable
>
哈咯啊
</el-dialog>
</template>
<script setup>
const props = defineProps({
modelValue: {
type: Boolean,
default: false
}
})
const emit = defineEmits(['update:modelValue'])
const dialogVisible = computed({
get: () => props.modelValue,
set: (val) => emit('update:modelValue', val)
})
</script>
3、defineModel (3.4+) 官方推荐
<template>
<el-dialog
v-model="dialogVisible"
title="Tips"
width="800"
draggable
>
哈咯啊
</el-dialog>
</template>
<script setup>
const dialogVisible = defineModel({
type: Boolean,
required: true,
default: false,
})
</script>
export default defineConfig({
plugins: [
vue({
script:{
defineModel: true
}
}),
vueJsx(),
],
})
4、TS泛型用法(3.3+)
<script setup>
const emit = defineEmits<{
"update:modelValue":[value:boolean]
}>()
</script>