.vue文件中未定义的属性或方法 [英] Property or method not defined in .vue file
问题描述
在我开始添加JavaScript之前,我的应用程序中的所有内容都能正常运行.现在,我不断在控制台中出现错误.
Everything in my app was working perfectly fine until I began to add my javascript. Now I continuously get errors in the console.
我收到此错误:
属性或方法"show"未在实例上定义,但在渲染期间被引用.通过初始化属性,确保该属性在data选项中或对于基于类的组件都是反应性的.
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"警报提示单击".
Desired Outcome: Click on "loginBtn" alert prompts "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>
推荐答案
您正在使用 vue-loader
.
You are using a Single-File Component (a .vue
file), which is a file format for a Vue component definition used by vue-loader
.
.vue
文件的脚本部分(在<script>
标记内)应该导出一个对象,该对象指定Vue实例的定义.
The script section of a .vue
file (what's inside the <script>
tag) should export an object specifying the definition of the Vue instance.
脚本必须导出Vue.js组件选项对象.还支持导出由Vue.extend()创建的扩展构造函数,但首选纯对象.
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
方法的原因.
You are currently only exporting { name: 'app' }
, which is why Vue can't find the show
method.
您的<script>
部分应如下所示:
<script>
export default {
name: 'app',
data() {
return { n: 0 }
},
methods: {
show: function(event) {
targetId = event.currentTarget.id;
alert('click')
}
}
}
</script>
还请注意,导出对象的data
属性需要是一个返回数据属性的函数. 请参阅Vue普通初学者的为什么data
为什么需要成为函数"部分陷阱页面.
Note also that the data
property of the object exported needs to be a function returning the data properties. See the "Why does data
need to be a function" section of Vue's Common Beginner Gotchas page.
这篇关于.vue文件中未定义的属性或方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!