在我开始添加我的 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 实例定义的对象。
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/