VueJS change v-model variable from child

2019-08-04 14:47发布

问题:

I'm trying to change the v-model of a component by the parent component most I'm not getting.

In the parent component I have a showProgress variable, I want it when I change it to true the child v-model <progress-modal> switch to true.

ProgressModal.vue

<template>
    <v-dialog v-model="show" persistent max-width="400">
        <v-card :dark="($theme === 'dark')">
            <v-card-title class="headline" v-text="title"></v-card-title>
            <v-divider></v-divider>
            <div class="text-xs-center mt-2">
                <v-progress-circular indeterminate :size="100" :color="$color"></v-progress-circular>
                <v-card-text v-text="text"></v-card-text>
            </div>
        </v-card>
    </v-dialog>
</template>

<script>
    export default {
        name: 'progress-modal',
        props: ['title', 'text'],
        data: () => ({
            show: true
        }),
        methods: {

        }
    }
</script>

I already tried to use

<progress-modal v-model="showProgress">

Instead of v-model in v-dialog but it does not work :(

回答1:

To enable usage of v-model by the parent, you have to define a value prop in the child and use it.

<template>
    <v-dialog v-model="value" persistent max-width="400">

...
</template>
<script>
    export default {
        name: 'progress-modal',
        props: ['title', 'text', 'value'], // added 'value'
        data: () => ({
...
</script>

This way, when you use:

<progress-modal v-model="showProgress">

...the value inside progress-modal will have the value of parent's showProgress.


Keeping it named show

To use other internal name instead of value you can declare the model option in the component.

<template>
    <v-dialog v-model="show" persistent max-width="400">

...
</template>
<script>
    export default {
        name: 'progress-modal',
        props: ['title', 'text', 'show'],    // added 'show'
        model: {                             // added model option
          prop: 'show'                       //
        },                                   //
        data: () => ({
        }),                                  // in this case, remove show from data
...
</script>


回答2:

Pass value prop as value to v-dialog component, and re-emit input from v-dialog component:

//CustomDialog.vue
<v-dialog :value="value" @input="$emit('input', $event)">

</v-dialog>
...
props:['value']

and add v-model to your parent (custom dialog)

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

Example