vue+ts+element-plus 父组件调用子组件,子组件为el-dialog。无法弹出子组件?

新手上路,请多包涵

\\#\\#\\# 题目描述
使用vue+ts+element-plus练习,在使用el-dialog时遇到问题。想法是子组件为el-dialog,父组件调用子组件弹出对话框。因为element-plus中el-dialog的v-model无法赋值为props,即无法直接使用父组件的传值。所以在子组件中增加变量show赋值给v-model,watch父组件的传值来改变show的值,来达到显示,关闭对话框的效果。目前的问题是在watch中改变了show的值为true,但对话框不显示。

\\#\\#\\# 相关代码
父组件
<CreateForm

visible={testFixture.createTrainVisible} >

</CreateForm>

子组件
<template>

<el-dialog title="创建列车" v-model="show" :show-close="false" width="35%">
    <el-form
        ref="planForm"
        :model="planForm"
        :rules="rules"
        :label-position="labelPosition"
        label-width="110px"
        size="small"
    >
        <el-form-item label="车组号" prop="trainGroupId">
                <el-input
                    v-model="inputGroupId"
                    placeholder="请输入车组号"
                ></el-input>
        </el-form-item>
    </el-form>
    <template #footer>
    <span class="dialog-footer">
        <el-button @click="show = false">取 消</el-button>
        <el-button type="primary" @click="onEnter">确 定</el-button>
    </span>
    </template>
</el-dialog>

</template>

<script lang='ts'>
import { defineComponent, PropType, ref, watch } from 'vue';

export default defineComponent({

name: 'CreateTrainForm',
props: {
    visible: {
        type: Boolean,
    },
    updateShow: {
        type: Function as PropType<(show: boolean) => void>,
    },
},
setup(props, context) {
    let show: boolean = false;

    watch(
        () => props.visible,
        () => {
            if (props.visible) {
                show = true;
                console.log('show status '+show);
            }
        }
    );
    return {
        show,
        inputGroupId: ref(''),
    };
},

});
</script>

阅读 7k
1 个回答

主要原因是你setup里定义的变量show没有添加响应式。
需要把初始值用ref包裹才能使变量被vue的响应式监听到:

const show = ref(false)

然后改变变量值的时候需要使用show.value:

show.value = true
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题