【问题标题】:Property or method "isOpen" is not defined on the instance but referenced during render属性或方法“isOpen”未在实例上定义,但在渲染期间引用
【发布时间】:2020-09-02 16:12:42
【问题描述】:

我对 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.js modal-dialog vue-component


    【解决方案1】:

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

    在父级中:

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

    在孩子身上:

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

    【讨论】:

    • 感谢您的重播,但我看不出有什么不同。语法错误是什么?
    • 在孩子的data() 之前有一个}。此外,.then 不是必需的。
    • Majed Badawi 你是对的,.then 触发了错误。谢谢!
    【解决方案2】:

    您的示例中缺少某些内容,因为根据您提供给我们的内容,它按预期工作:

    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>

    【讨论】:

    • 它确实有效,因为您没有像我一样在openMyModal() 中调用承诺。感谢您的回复!
    猜你喜欢
    • 2017-06-16
    • 2018-06-22
    • 2020-09-02
    • 2018-09-17
    • 2020-09-05
    • 2022-01-24
    • 2019-08-08
    • 2019-02-28
    • 2018-07-13
    相关资源
    最近更新 更多