Vue中的methods與computed有什么區別?很多新手對此不是很清楚,為了幫助大家解決這個難題,下面小編將為大家詳細講解,有這方面需求的人可以來學習下,希望你能有所收獲。
設計一個計算成績和的案例:
<!DOCTYPE html><html lang="en">
<head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>計算屬性與監聽器</title> <!-- 引入Vue.js --> <script src="./node_modules/vue/dist/vue.js"></script> </head> <body> <div id="app"> 數學:<input type="text" v-model="mathScore"> 英語:<input type="text" v-model="englishScore"><br> <!-- 注意:調用methods的方法一定要加括號 --> 總分(methods方式):<input type="text" v-model="sumScore()"><br> <!-- 注意:調用computed里面的方法不要加括號 --> 總分(computed,純get方式):<input type="text" v-model="sumScore1"><br> 總分(computed,get+set方式):<input type="text" v-model="sumScore2"> </div> <script> var vm = new Vue({ el: '#app', data: { mathScore: 80, englishScore: 60 }, methods: { sumScore: function () { console.log("methods方式調用!"); return (this.mathScore - 0) + (this.englishScore - 0); } }, computed: { // 默認是純get方式,也是單項綁定 sumScore1: function () { console.log("compute的純get方式調用"); return (this.mathScore - 0) + (this.englishScore - 0); }, // 采用get加set方式 sumScore2: { get: function () { console.log("compute的get方式調用"); return (this.mathScore - 0) + (this.englishScore - 0); }, // 當在輸入框中更改了總分后,兩項成績就會分別取到新總分的平均值,從而實現雙向綁定 set: function (newValue) { console.log("compute的set方式調用"); var avgScore = newValue / 2; this.mathScore = avgScore; this.englishScore = avgScore; } } } }) </script> </body> </html>
總結methods與computed區別:
看完上述內容是否對您有幫助呢?如果還想對相關知識有進一步的了解或閱讀更多相關文章,請關注億速云行業資訊頻道,感謝您對億速云的支持。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。