[ElementPlus] 父子组件弹窗3-用到ref, defineProps, defineEmits

76 阅读1分钟

父组件

<template>
    <div>
        <el-button @click="showDia">手写弹窗导入</el-button>

        <importTestSub :isShowDia="isShowDia" @updateShow="updateShow" />
    </div>
</template>

<script setup>
import { ref } from 'vue'
import importTestSub from './importTestSub.vue'

const isShowDia = ref(false)

const showDia = () => {
    isShowDia.value = true
}

// 父元素定义一个自定义事件, 用于当子元素更新开关值时,同步到父元素
const updateShow = (value) => {
    isShowDia.value = value
}
</script>

子组件

<template>
    <div>
        <el-dialog v-model="subShow" title="Shipping address">
            <el-form :model="form">
                <el-form-item label="Promotion name" :label-width="formLabelWidth">
                    <el-input v-model="form.name" autocomplete="off" />
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="updateShow(false)">Cancel</el-button>
                    <el-button > Confirm</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { reactive, ref, watchEffect } from 'vue'

const dialogTableVisible = ref(false)

const form = reactive({
  name: ''
})

// vue3接收props
const props = defineProps({
    isShowDia: Boolean
})

let subShow = ref(props.isShowDia) // 本地变量

// 使用watchEffect监听父组件值的变化
watchEffect(() => {
    subShow.value = props.isShowDia
})

// emit
const emit = defineEmits(['updateShow'])

// 当子组件的值更改时, 传递给父组件
const updateShow = (value) => {
    subShow.value = value
    emit('updateShow', value)
}

console.log('@@@', subShow);
</script>