溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Vue中的methods與computed有什么區別

發布時間:2020-10-23 16:43:28 來源:億速云 閱讀:378 作者:Leah 欄目:web開發

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區別:

  • 1.調用方式不同。computed直接以對象屬性方式調用,不需要加括號,而methods必須要函數執行才可以得到結果。
  • 2.綁定方式不同。methods與compute純get方式都是單向綁定,不可以更改輸入框中的值。compute的get與set方式是真正的雙向綁定。
  • 3.是否存在緩存。methods沒有緩存,調用相同的值計算還是會重新計算。competed有緩存,在值不變的情況下不會再次計算,而是直接使用緩存中的值。

看完上述內容是否對您有幫助呢?如果還想對相關知識有進一步的了解或閱讀更多相關文章,請關注億速云行業資訊頻道,感謝您對億速云的支持。

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女