猿问

vue中父子组件交互问题

问题描述

有这样一个简单的需求: 页面有一个按钮, 点击会有一个弹窗, 弹窗上有个关闭按钮, 点击可以关闭这个弹窗

vue的组件来做大约是这样的

<component-parent>
    <component-child>
        ....我是内容....        <button>点我关闭</button>
    </component-child>
    
    <button>点我打开</button></component-parent>

问题出现的环境背景及自己尝试过哪些方法

我的实现方式是这样的:
  • 打开操作(父组件操作):

    show(){
        this.isShow = true
        .....做其他的事情....
    }hide(){
        this.isShow = false
    }
  • 关闭操作(子组件操作):

    this.$parent.hide()

这样做能实现功能, 但是就是不太优雅, 因为这样父组件必须实现子组件调用的方法/属性, 耦合会很高

emit我也想过, 但我觉得这样更不好


牧羊人nacy
浏览 1849回答 2
2回答

撒科打诨

sync 修饰符了解一下。<component-child&nbsp;:visible.sync="isShow"></component-child>//&nbsp;子组件内的关闭方法handleClose()&nbsp;{&nbsp;&nbsp;&nbsp;this.$emit('update:visible',&nbsp;false); }

交互式爱情

<component-child @cancel=cancel></component-child>父组件中定义cancel函数
随时随地看视频慕课网APP

相关分类

Vue.js
我要回答