0
votes

I am relatively new to vue.js. I am trying to create a modal dialog that has an initial displayed state set to false. This dialog is used in another component like it is shown billow. I cannot figure out why the data is isOpen is undefined

// My main component here
<template>
 <button @click="openMyModal">Open</button>
 <MyDialog ref="dialog"/>
</template>
<script>
...
methods: {
 openMyModal(){
    this.$refs.dialog.open().then((confirm) => {
          console.log("confirm", confirm)
          return true
        }).catch();
 }
}
...
</script>
<template>
  <div class="overlay" v-if="isOpen">
    <div class="modal">
     <h1>My modal dialog here</h1>
    </div>
   </div>
 </div>
</template>
<script>
export default {
    name: 'my-dialog'
}
 data () {
      return {
        isOpen: false
        ...
      }
 }
 methods() {
  open() {
        this.isOpen = true;
        ...
      },
  close() {
        this.isOpen = false;
      },
}
</script>
2

2 Answers

1
votes

It is mostly because of syntax errors. Here is an example after debugging your code:

In the parent:

methods: {
    openMyModal() {
      this.$refs.dialog.open();
    }
}

In the child:

export default {
  name: "my-dialog",
  data() {
    return {
      isOpen: false
    };
  },
  methods: {
    open() {
      this.isOpen = true;
    },
    close() {
      this.isOpen = false;
    }
  }
};
0
votes

Something is missing in your example because from what you gave to us it's working as intended:

Vue.component('MyDialog', {
  template: `
    <div>
      isOpen: {{ isOpen }}
      <div v-if="isOpen">
        <h1>My modal dialog here</h1>
      </div>
    </div>
  `,
  data () {
    return {
      isOpen: false
    }
  },
  methods: {
    open() {
      this.isOpen = true;
    },
    close() {
      this.isOpen = false;
    },
  }
})

Vue.config.productionTip = false

new Vue({
  el: '#app',
  template: `
    <div>
      <button @click="openMyModal">Open</button>
      <button @click="closeMyModal">Close</button>
      <MyDialog ref="dialog"/>
    </div>
  `,
  methods: {
    openMyModal(){
      this.$refs.dialog.open()
    },
    closeMyModal(){
      this.$refs.dialog.close()
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<body>
   <div id="app" />
</body>