Vue JS. Toggle child component modal

给你一囗甜甜゛ 提交于 2019-12-11 12:25:09

问题


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?

回答1:


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



来源:https://stackoverflow.com/questions/48490440/vue-js-toggle-child-component-modal

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!