属性 或 .vue 文件中未定义方法

Property or method not defined in .vue file

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

我收到这个错误:

Property or method "show" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property.

还有这个错误:

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

预期结果:单击 "loginBtn" 警报提示 "click"。


我的代码:

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

您正在使用 Single-File Component (a .vue file), which is a file format for a Vue component definition used by vue-loader.

.vue 文件的脚本部分(<script> 标签内的内容)应该导出一个指定 Vue 实例定义的对象。

From the documentation:

The script must export a Vue.js component options object. Exporting an extended constructor created by Vue.extend() is also supported, but a plain object is preferred.


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

您的 <script> 部分应如下所示:

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