Search code examples
vue.jscomponents

How to open and close a modal within a child component using a prop, vuejs?


I currently have the following child component

  <Edit
     @fetchInfo="fetchInfo"
     :agencyData="agency"
     :dialogEdit.sync="dialogEdit"
   ></Edit>

Which basically contains a modal

initially it is false, so as not to show the modal:

data(){
 return {
    dialogEdit: false
 }
}

by a method I do:

open(){
  this.dialogEdit = true;
}

In my <Edit></Edit> component I have:

<el-dialog title="Editar" :visible.sync="dialogEdit" width="60%">
</el-dialog>

and received with prop:

 props: ["dialogEdit"],

But then when closing the modal from the child component I receive an error

[Vue warn]: Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders. Instead, use a data or computed property based on the prop's value. Prop being mutated: "dialogEdit"


Solution

  • First of all, apparently you are using Element UI.

    But, as the error suggests, you are modifying dialogEdit directly. When closing the element ui modal by clicking the X, dialogEdit becomes false. You could solve this using computed property, like suggested for example in this answer.

    Since you are using Element UI you also have another possibility to solve this. The dialog has the event before-close which is fired before the modal is closed. There you can emit the new boolean value for dialogEdit to the parent. So keep the :dialogEdit.sync="dialogEdit" in child tag and add the before-close to the dialog and a function to handle, where you emit the new false value:

    <el-dialog title="Editar" :before-close="handleClose" ....>
    

    JS:

    methods: {
      handleClose() {
        this.$emit('update:dialogEdit', false);
      }
    },
    

    If you have some button in your modal to close the modal, you can add the same function there:

    <el-button type="primary" @click="handleClose">Close</el-button>
    

    SANDBOX