2017-04-20 32 views
2

我是vue.js新手,出現問題, 我有一個計算函數,用於提醒Word反轉, 我讓這個函數能夠點擊按鈕,但它工作正常在頁面加載,所以是什麼問題。 這是vue.js代碼,vuejs中的計算函數無法與我一起工作

new Vue({ 
el: '#computed', 
data: { 
    word: 'welcome', 
}, 
computed: { 
    alertRev: function() { 
     // get the word reversed 
     alert (this.word.split('').reverse().join('')); 
    }, 
}}); 

這是HTML代碼:

<div id="computed"> 
    <button @click="alertRev">reverse the word</button> 
</div> 

這是的jsfiddle鏈接 Link to code

+0

計算是一個屬性,而不是一個方法。當你打開你的小提琴時,它會提醒相反的情況,因爲它是在Vue創建時計算的。但計算並不是一種方法。這就是爲什麼當你點擊時,沒有任何反應。如果你想點擊執行警報,然後製作一個方法。 – Bert

+0

非常感謝,bert, 我明白 – shennawy

+0

jsFiddle的合作選項非常酷。我不知道它可以做到這一點:) – Bert

回答

1

由於@BertEvans指出,一個方法將實現你想做。

我的理解是,一個計算屬性通常會返回一個函數的結果,而不是執行一個動作,比如一個警報。從Vuejs文檔無恥變形例(https://vuejs.org/v2/guide/computed.html):

new Vue({ 
 
    el: '#computed', 
 
    data: { 
 
    word: 'welcome', 
 
    }, 
 
    computed: { 
 
    reversedMessage: function() { 
 
     // get the word reversed, no alert 
 
     return this.word.split('').reverse().join(''); 
 
    }, 
 
    } 
 
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.2.6/vue.min.js"></script> 
 
<div id="computed" style="font-family: arial;"> 
 
    Type the word: <input type="text" v-model="word"> 
 
    <br /> 
 
    <br /> Reversed: {{ reversedMessage }} 
 
</div>

的方法,例如:

new Vue({ 
 
    el: '#computed', 
 
    data: { 
 
    word: 'welcome', 
 
    }, 
 
    methods: { 
 
    alertRev: function() { 
 
     // get the word reversed 
 
     alert(this.word.split('').reverse().join('')); 
 
    }, 
 
    } 
 
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.2.6/vue.min.js"></script> 
 
<div id="computed"> 
 
    Word: {{ word }} 
 
    <br /> 
 
    <br /> 
 
    <button @click="alertRev">Reverse the word (alert)</button> 
 
</div>

順便說一句,計算性能不是非常方便與異步操作。

希望這並不強調你可以用溼拖把在郵票背面寫下我對Vuejs的瞭解。

相關問題