2017-10-16 48 views
1

我的应用程序中的所有内容都工作得很好,直到我开始添加我的JavaScript。现在我不断在控制台中发现错误。.vue文件中未定义的属性或方法

我得到这个错误:

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> 

回答

3

您正在使用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.

+0

Yayyy! Tysm一直在寻找几个小时,但有很多不同的方法来实现这个我想。此外,我没有发现其他人解释说,它应该在出口内,大多数人说创建('新Vue') – hannacreed

+0

很高兴帮助!是的,'.vue'文件遵循'vue-loader'用来抽取一些样板代码的特定格式(例如需要通过'new Vue'实例化)。我编辑了我的帖子,链接到一些您可能会发现有帮助的文档。 – thanksd

相关问题