Home > other >  Update property value of child component from parent component
Update property value of child component from parent component

Time:11-11

I have a parent component that has a button element. If user clicks that button, a dialog component should appear. The child component is the dialog component. However, the dialog won't open. This is how I propagate props to my child component:

Parent component (template):

<v-btn
 color="primary"
 elevation="5"
 @click="openCreateDialog = true"
 small
>
 <v-icon left>
   mdi-plus
 </v-icon>
  Create
</v-btn>
<create-reservation-dialog :open="openCreateDialog" />

Child component (template):

<v-dialog v-model="openDialog" width="300">
  <span>Opened</span>
</v-dialog>

Child component (JS):

export default Vue.extend({
name: "CreateReservationDialog",
props: {
  open: {
    type: Boolean,
    required: true,
  },
},
data() {
  return {
    openDialog: this.open,
  }
},
});

Any ideas how can I fix this? Should I bind some method that will update openDialog variable in child? If so how?

Thank you in advance.

CodePudding user response:

on clicking you are just updating the property value but it will not reload the dialog component. You can add v-if="openCreateDialog" in create-reservation-dialog to render it dynamically.

Live Demo (Please notice here, how mounted hook called in the child component) :

Vue.component('custom-dialog', {
  props: ['open'],
  template: '<p>{{ open }}</p>',
  mounted() {
    console.log('popup called');
  }
});

var app = new Vue({
  el: '#app',
  data: {
    openCreateDialog: false
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <button @click="openCreateDialog = true">Open Dialog</button>
  <custom-dialog v-if="openCreateDialog" :open="openCreateDialog">
  </custom-dialog>
</div>

  • Related