Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.4k views
in Technique[技术] by (71.8m points)

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>


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

const show = ref(false)

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

show.value = true

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...