# Vue學習#9 computed & watch ###### tags: `Vue 直播班 - 2022 春季班` `Vue` ## Methods Vue Instance 在初始化時可設定選項物件,其中可設定 method,執行一些動作 ```=Vue const app={ data(){ }, methods:{ // <-this function(){ } }, mounted(){ } } ``` ## computed  使用方式: 不需要再 `data()` 宣告變數,在 computed 中 可以宣告變數並可直接渲染在 html 上面 以上圖為例: 每當 total() 的內容發生變化就會自動啟動函式內的程式! * 是一個物件 * 監聽多個資料,將資料處理完並渲染到畫面上 * 一定要 return * 寫在 computed 的函式的變數都會自動監聽,當其中一個變數有變更時,就會自動再次啟動該函式 ### 什麼是 Getter 簡單來說就是 我們將 `data` 的資料取出來經過 `computed` 處理後在渲染到畫面上 <font color="red"> Getter 的資料只能 readonly 不能夠進行寫入 </font> ### 那 Setter 呢 那 Setter 就是相反過來,將資料經過 `computed` 之後再寫回 `data` 中 <font color="red"> 跟 Getter 相反可以進行寫入資料 </font> ### 使用 Getter & Setter 的重點 1. 原本 `computed` 放的是函式需要改成 <font color="red">物件</font> 2. 使用 getter , 需要寫 get() 函式 3. 使用 setter , 需要寫 set() 函式 [computed 範例](https://github.com/Danny-1211/VUE-review/tree/main/computed) ### computed 跟 methods的差別 computed 是根據相依的資料改變時才做計算,而 method 是不管有無相依都會計算 <font color='red'>**需要每次更新,就用 method 在意效能,就用 computed**</font> ## watch ```=vue const app={ data(){ }, methods:{ }, watch: { tempData: function () { // 監聽值 : function(可放入參數){當值改變時要做的事} if (this.tempData.id !== this.tempdataModal.id) { this.tempdataModal = this.tempData; } } }, mounted(){ } } ``` * 是一個方法 * 監聽單一資料,並可以改變資料內容 * Watch 可讓我們監視某個值,當這個值變動的時候,就去做某些事情 ### computed 與 watch 差別 #### watch 1. 監聽單一 "變數" 觸發事件 2. 該函式可以操作多個變數 #### computed 1. 監聽多個變數觸發事件 2. 會產生一個值 ## 參考 [Vue.js: Methods 與事件處理 (Event Handling)](https://cythilya.github.io/2017/04/17/vue-methods-and-event-handling/) [Vue.js: 計算屬性 Computed](https://cythilya.github.io/2017/04/15/vue-computed/) [Vue.js: Watch](https://cythilya.github.io/2017/04/15/vue-watch/)
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up