Interaction between parent and child components in vue

problem description

there is such a simple requirement: there is a button on the page, there will be a pop-up window when clicked, and there is a close button on the pop-up window. Click to close this pop-up window

use the components of vue to do something like this

<component-parent>
    <component-child>
        ........
        <button></button>
    </component-child>
    
    <button></button>
</component-parent>

the environmental background of the problems and what methods you have tried

my implementation is as follows:
  • Open operation (parent component operation):

    show(){
        this.isShow = true
        .........
    }
    hide(){
        this.isShow = false
    }
  • close operation (sub-component operation):

       this.$parent.hide()

this can achieve functionality, but it is not very elegant, because in this way the parent component must implement the methods / properties called by the child component, and the coupling will be very high

I"ve thought about emit, too, but I think it"s even worse.

what result do you expect? What is the error message actually seen?

hope to find an optimal solution, only operate in the child component, do not rely on the parent component, thank you!

Mar.30,2021

Learn about the

sync modifier .

<component-child :visible.sync="isShow"></component-child>
// 
handleClose() {
   this.$emit('update:visible', false);
}

< component-child @ cancel=cancel > < / component-child >
the cancel function is defined in the parent component


you can write the parameter isShow in the child component to control the method of the child component, and then use $emit to transfer it out, so that it does not depend on the parameters of the parent component. Generally, encapsulated components write


.

you need a popupWindowManager class to manage all pop-up windows.

the parent component calls this

popupWindowManager.popup(closeHandler)
Menu