【问题标题】:Property or method not defined in .vue file.vue 文件中未定义的属性或方法
【发布时间】:2017-10-16 16:33:09
【问题描述】:

在我开始添加我的 javascript 之前,我的应用程序中的一切都运行良好。现在我在控制台中不断收到错误。

我收到此错误:

属性或方法“show”未在实例上定义,但在渲染期间被引用。通过初始化该属性,确保该属性是反应性的,无论是在数据选项中,还是对于基于类的组件。

还有这个错误:

TypeError: _vm.show is not a function
  at click App.vue?d98c:25
  at HTMLButtonElement.invoker vue.esm.js?efeb:1906

期望结果:点击“loginBtn”警报提示“点击”。


我的代码:

// app.vue script 
export default {
  name: 'app'
}

var show = new Vue({
  el: '#loginBtn',
  data: {
    n: 0
  },
  methods: {
    show: function(event) {
      targetId = event.currentTarget.id;
      alert('click')
    }
  }
})

<!-- the button -->
<template>
  <div>
    <button v-on:click="show($event)" id="loginBtn">Login</button>
  </div>
</template>

【问题讨论】:

    标签: javascript vue.js vuejs2 vue-loader


    【解决方案1】:

    您正在使用Single-File Component(.vue 文件),这是vue-loader 使用的 Vue 组件定义的文件格式。

    .vue 文件的脚本部分(&lt;script&gt; 标记内的内容)应该导出一个指定 Vue 实例定义的对象。

    From the documentation:

    脚本必须导出一个 Vue.js 组件选项对象。还支持导出由 Vue.extend() 创建的扩展构造函数,但首选普通对象。


    你目前只导出{ name: 'app' },这就是Vue找不到show方法的原因。

    您的&lt;script&gt; 部分应如下所示:

    <script>
      export default {
        name: 'app',
        data() {
          return { n: 0 }
        },
        methods: {
          show: function(event) {
            targetId = event.currentTarget.id;
            alert('click')
          }
        }
      }
    </script>
    

    还要注意,导出对象的data 属性必须是返回数据属性的函数。 See the "Why does data need to be a function" section of Vue's Common Beginner Gotchas page.

    【讨论】:

    • 耶耶! Tysm,一直在寻找几个小时,但我想有很多不同的方法可以实现这一点。此外,我发现没有其他人解释它应该在导出中,大多数人说要创建一个('new Vue')
    • 很高兴为您提供帮助!是的,.vue 文件遵循vue-loader 用来抽象出一些样板代码的特定格式(例如需要通过new Vue 实例化)。我编辑了我的帖子以链接到一些您可能会觉得有帮助的文档。
    猜你喜欢
    • 2020-03-24
    • 1970-01-01
    • 2021-07-17
    • 2021-04-20
    • 2019-03-29
    • 1970-01-01
    • 1970-01-01
    • 2021-03-05
    • 2019-12-04
    相关资源
    最近更新 更多