user1434702
user1434702

Reputation: 829

How to close dialog by self with vuejs2?

I am writing a dialog component, i don't know how to close dialog by self.

<template>
  <div class="dialog" v-show="visible">
    ...
    <button @click="close">Close</button>
  </div>
</template>
<script>
  {
    props: {visible: {type: Boolean, default: false}},
    methods: {
      close () {
        // this.visible = false //It will get vue warn
      }
    }
  }
</script>

So, how to close the dialog in my component, i can't update visible prop, i will get a error.

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: "visible"

Upvotes: 0

Views: 2241

Answers (2)

Vamsi Krishna
Vamsi Krishna

Reputation: 31352

Props are one way data flow

You should not mutate the prop received from a parent component in the child component

So emit an custom event to mutate the prop in parent component itself

<template>
  <div class="dialog" v-show="visible">
    ...
    <button @click="close">Close</button>
  </div>
</template>
<script>
  {
    props: {visible: {type: Boolean, default: false}},
    methods: {
      close () {
        // this.visible = false //It will get vue warn
        this.$emit('close-dialog')
      }
    }
  }
</script> 

parent component

<template>
    <div>
    <my-dialozg @close-dialog="visible = false" :visible="visible"><my-dialog>
    </div>
</template>

Setup an event listener close-dialog on the dialog component and set the data property visible that you pass as a prop to false. You can do this inline as shown above or extract it into a method also

Upvotes: 2

samayo
samayo

Reputation: 16495

In vuejs, child component can not modify the parents property directly.

You can use events/event listeners for that. But since your example is simple you don't need an event for that.

Demo: https://jsfiddle.net/samayo/943bx5px/28/

Instead, you can pass the prop visible to your component as :visisble="visible" and watch the state change as:

watch: {
  visible (val) {
    if(!val) {
        // close
    }else{
        open
    }
  }
}

Now, if visisble is toggled to false from the parent, your modal will not be visible.

Upvotes: 1

Related Questions