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

标签 javascript vue.js vuejs2 vue-loader

在我开始添加我的 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”警报提示“点击”。


我的代码:

// 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 (.vue 文件),这是 vue-loader 使用的 Vue 组件定义的文件格式。 .

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

关于javascript - .vue 文件中未定义的属性或方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46775024/

相关文章:

javascript - 2 个 Html 表单如何共享 1 个隐藏字段?

javascript - 在父元素外部单击时删除类

javascript - xmlhttprequest欺骗referer然后重定向到另一个页面?

node.js - 如何使用单文件组件访问 vm.$el 属性?

typescript - 为什么 getter/setter 在 vue typescript 类组件中无法正常工作

vue.js - 在 Vuejs 2 中单击按钮时将完成更改为 true

typescript - Vue Typescript 组件类属性初始化器的最佳实践

javascript - 有效 url 的正则表达式

javascript - 搜索 "Cannot use ' 时出现 '0' 错误,这在本地主机上不会发生

vue.js - 如何在 Vue Web 组件中使用 vue-i18n?