Welcome to 16892 Developer Community-Open, Learning,Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

\#\#\# 题目描述
使用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>


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
4.0k views
Welcome To Ask or Share your Answers For Others

1 Answer

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

const show = ref(false)

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

show.value = true

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to 16892 Developer Community-Open, Learning and Share
...