當前位置:
首頁 >
Vue中methods与computed区别
發布時間:2024/1/1
36
豆豆
生活随笔
收集整理的這篇文章主要介紹了
Vue中methods与computed区别
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
核心區別
實例:
<script>Vue.createApp({data() {return {message: '我是消息,'}},methods: {methodTest() {return this.message + '現在我用的是methods'}},computed: {computedTest() {return this.message + '現在我用的是computed'}},}).mount('#app')</script> <div id="app"><h1>{{message}}</h1><p class="test1">{{methodTest}}</p><p class="test2-1">{{methodTest()}}</p><p class="test2-2">{{methodTest()}}</p><p class="test2-3">{{methodTest()}}</p><p class="test3-1">{{computedTest}}</p><p class="test3-2">{{computedTest}}</p></div>
可以看到,方法需要加括號,屬性不需要。
computed緩存
在上面的例子中,methods定義的方法是通過函數調用的形式訪問的,如果我們需要1000個methodTest的返回值,那么會造成資源浪費。如果更改了message的值,1000個methodTest每一個又需要重新計算。
所以,對于任何復雜邏輯,你都應當使用計算屬性,例如一些復雜度很高的算法,應當使用computed。
computed依賴于data中的數據,只有在它的相關依賴數據發生改變時才會重新求值。
在上例中,computed定義computedTest方法只做一次計算,返回一個值;在隨后的代碼編寫中,只要computedTest方法依賴的message數據不發生改變,computedTest方法是不會重新計算的,也就是說test3-1,test3-2是直接拿到了返回值,并不是computedTest方法重新計算的結果。
總結
以上是生活随笔為你收集整理的Vue中methods与computed区别的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Arduino 薄膜压力传感器 实验
- 下一篇: Chrome 自动化交互利器:用 tam