2017-10-16 549 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

相關問題