iT邦幫忙

2021 iThome 鐵人賽

DAY 11
0
自我挑戰組

Vue.js系列 第 11

Watch

  • 分享至 

  • xImage
  •  

今天要介紹的是watch屬性

Watch他跟computed最大的不同是他沒有cache的機制,那watch是要做什麼的呢?
我們先來看看官網的介紹吧!

Vue does provide a more generic way to observe and react to data changes on a Vue instance: watch properties. When you have some data that needs to change based on some other data, it is tempting to overuse watch. However, it is often a better idea to use a computed property rather than an imperative watch callback.

While computed properties are more appropriate in most cases, there are times when a custom watcher is necessary. That’s why Vue provides a more generic way to react to data changes through the watch option. This is most useful when you want to perform asynchronous or expensive operations in response to changing data.

從官網的介紹中我們可以知道watch它可以觀察和監聽資料的變動,可是如果你是要做資料對其它資料的變動時使用computed會是比較好的選擇,因為在這種情況下使用watch很容易導致我們過度使用,看到這裡你可能會想說那我們就都使用computed就好啦,為什麼還要使用watch呢?從官網中的另一段也就是這裡擷取的第二段它又告訴我們雖然computed在很多情況下都適用,但是當我們在執行非同步或是比較複雜的運算時,我們還是需要使用watch屬性去監聽資料的變動,所以在執行非同步或是資料一直改變需要一直監聽的時候,使用watch就很合適

在今天的範例中還有使用到watch中的deep屬性以及localStorage
deep屬性是去做深度監聽,也就是他會去監聽每個參數,而localStorage它是可以將我們的資料儲存在網頁中,當使用者關閉瀏覽器在開啟同一個瀏覽器時資料也都會存在喔!當你點開application會發現我們輸入的資料會存在那裡面
https://ithelp.ithome.com.tw/upload/images/20210915/20139183Rg9taZuCAg.jpg

Demo
github


上一篇
Computed vs Methods
下一篇
v-show vs v-if
系列文
Vue.js30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言