iT邦幫忙

2021 iThome 鐵人賽

DAY 10
0
自我挑戰組

Vue.js系列 第 10

Computed vs Methods

昨天已經把JSON檔建置好了!今天就可以取用JSON檔的資料然後實作出Methods和Computed的差別

首先要注意的是,我們要取得JSON檔的資料需要利用Axios發送GET請求,所以在這裡我們需要加入Axios的CDN

<!-- Axios 的 CDN -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.21.1/axios.min.js"></script>

進入實作前我們先來看一段官網對於Computed和Methods的比較

the difference is that computed properties are cached based on their reactive dependencies. A computed property will only re-evaluate when some of its reactive dependencies have changed. In comparison, a method invocation will always run the function whenever a re-render happens. In cases where you do not want caching, use a method instead.

從官網中我們可以知道computed他具有緩存的機制,也就是當你的原始資料沒有做改變時它就會cache住,都不會重新去做計算,但是Methods沒有緩存的機制所以只要呼叫一次就會重新計算一次,所以如果希望資料不要緩存的話就使用methods

接下來我們用實際的例子開Console來比較看看就更能體會他們的差異了!
https://ithelp.ithome.com.tw/upload/images/20210919/20139183enVnJFrni1.jpg

https://ithelp.ithome.com.tw/upload/images/20210919/20139183crNHs1yDa8.jpg
從Console中,我們可以看出Methods屬性只要我們切換一個類別時它就會重新去計算一次,但是computed是當我們切換類別時他都不會有任何動靜,也就是說它不會因為切換而重新去計算,當然這是因為在今天的範例中,computed的部分使用的是用下拉式選單去做選取,所以沒有讓使用者去做資料的修改,才會在使用computed的屬性時永遠都不會重新算

Computed_Demo
Methods_Demo
github


上一篇
JSON介紹
下一篇
Watch
系列文
Vue.js30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言