首页 > 解决方案 > 属性或方法“isOpen”未在实例上定义,但在渲染期间被引用

问题描述

我对 vue.js 比较陌生。我正在尝试创建一个初始显示状态设置为 false 的模式对话框。此对话框用于另一个组件,如波浪所示。我无法弄清楚为什么dataisOpenundefined

// 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>

标签: vue.jsmodal-dialogvue-component

解决方案


这主要是因为语法错误。这是调试代码后的示例:

在父级中:

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

在孩子身上:

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

推荐阅读