Svetoslav Dimitrov
Svetoslav Dimitrov

Reputation: 929

Vue JS. Toggle child component modal

Parent component:

<template>
    <v-btn v-on:click="dialog = !dialog">
    </v-btn>
</template
<script>
    export default {
        data: () => ({
           dialog: false
        }
</script

Child component:

<template>
    <v-layout>
        <v-dialog v-model="toggledialog">
            <v-btn color="green darken-1" flat="flat" 
            @click.native="toggledialog = false">Close</v-btn>
        </v-dialog>
    </v-layout>
</template>
<script>
    export default {
        data: () => ({
            toggledialog: false,
        }),
        watch: {
            dialog: function(){
                this.toggledialog = true
            },
        },
        props:['dialog']
}
</script>

This code works but I really don't like this workaround with watch.

Questions:

  1. How to open dialog in child component when v-model="toggledialog" if it doesn't watch for props:['dialog']?
  2. How to change dialog to false in parent component when I i change it in child component v-model="dialog" if in Vue JS it is not allowed to change props?

Upvotes: 1

Views: 4442

Answers (1)

Traxo
Traxo

Reputation: 19002

Pass value prop as value to v-dialog, and re-emit input v-dialog whenever you want to close it:

//CustomDialog.vue
<v-dialog :value="value" @input="$emit('input')">
    <v-btn color="green darken-1" flat="flat" 
        @click.native="$emit('input')"
    >Close</v-btn>
</v-dialog>
...
props:['value']

and add v-model to your parent

//Parent.vue
<custom-dialog v-model="dialog">

So no data and no watch

example

Upvotes: 4

Related Questions