Vite element-plus ts Dialog父子間的通訊

Vite element-plus ts Dialog 父傳子

父組件

v-model 的參數語法不會直接修改 props 的值 , 如何修改=>使用父組件 showDialog 父傳給子,@update:showDialog="showDialog = $event", 當 el-dialog 组件觸發 update:showDialog 事件時,子組件会觸發 update:showDialog 的自定義事件,並將新值作為参数傳遞給父組件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<template>
<!--點擊打開Dialog跳出框-->
<el-button @click="showDialog = true" type="primary">導出Excel</el-button>
<!--父組件 showDialogt父傳給子,@update:showDialog="showDialog = $event" -->
<Dialog
:showDialog="showDialog" @update:showDialog="showDialog = $event"/>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue';
const showDialog = ref(false);

</script>

子組件

子組件 :model-value="showDialog" @update:model-value="$emit('update:showDialog', $event)"

設定子組件關閉Dialog =>40 並需使用 let localShowDialog = ref(props.showDialog);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
<template>
<!--子組件 :model-value="showDialog" @update:model-value="$emit('update:showDialog', $event)"-->
<el-dialog
:model-value="showDialog"
@update:model-value="$emit('update:showDialog', $event)"
title="Notice"
width="30%"
destroy-on-close
center
>
<span>
Notice: before dialog gets opened for the first time this node and the one
bellow will not be rendered
</span>
<div>
<strong>Extra content (Not rendered)</strong>
</div>
<template #footer>
<span class="dialog-footer">
<!----試過這個方式可以註解A-->
<el-button @click="cancel">Cancel</el-button>
<el-button type="primary" @click="update">
Confirm
</el-button>
</span>
</template>
</el-dialog>
</template>


<script setup lang="ts">
import { ref, watch } from "vue";
interface showDialogType {
readonly showDialog: boolean;
}
const props: showDialogType = defineProps({
showDialog: {
type: Boolean,
default: false,
},
})

// 設定子組件關閉Dialog
let localShowDialog = ref(props.showDialog);
//監控
watch(() => props.showDialog, (newVal:boolean) => {
console.log('newVal',newVal)
localShowDialog.value = newVal;
})
// 子對父傳值
const emits = defineEmits(['update:showDialog']);
const update = () => {
emits('update:showDialog', false)
}
const cancel = () => {
localShowDialog.value = false;
emits('update:showDialog', false)
}
</script>