iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 10
1
Modern Web

忍住不打牌位,只要30天VueJS帶你上A牌系列 第 10

Day 10 你改我就變#像極了愛情,認識Computed

computed也是可以顧名思義知道它是針對資料做計算然後返回值,在了解computed之前我們先看看官網的說法

computed properties are cached based on their reactive dependencies.

計算屬性是基於它們的響應式依賴進行緩存的,白話文也就是說 computed 只會在它所依賴的數性值改變時重新計算,你改我就變 #像極了愛情

computed: {
    fullName () {
        return this.firstName + ' ' + this.lastName
    }
}

在我還在新手村的時候,我很常不曉得watch、computed 與 methods使用時機。
如上程式碼,假若我們要關注fullName變化更新,在computed只須寫一次。
如果要使用watch則需要關注firstName、lastName。
順道一提 methods 方法我們常會拿來寫複用多次的函數,最好的寫法應該是善用參數與回傳值,如下圖,可以看出哪個函數是不方便複用與單元測試。
https://ithelp.ithome.com.tw/upload/images/20200909/20129187xTtClfRk27.jpg

computed設定中可以分成 getter(讀取) 和 setter(設值),在沒有寫 setter 的情況下,computed 預設只有 getter ,也就是只能讀取,不能改變設值。另外,在 getter 中,要記得搭配使用 return 來把值返回出來。

computed: {
    fullName: {
        get: function () {
            return this.firstName + ' ' + this.lastName
        }
        set: function (newValue) {
            let name = newValue.split(' ')
            this.firstName = name[0]
            this.lastName = name[1]
        }
        
    }
}

有任何問題歡迎下方留言,如果喜歡我的文章別忘了按讚、訂閱追蹤加分享唷!!
---我是分隔線-----------------------------------------------------------
PollyPO技術-前端設計轉前端工程師-JS踩坑雜記 30 天
喬依司-實作經典 JavaScript 30
五百億-Vue CLI + Firebase 雲端資料庫 30天打造簡易部落格及後臺管理
eien_zheng-前端小嘍嘍的Golang學習旅程_The journey of learning Golang


上一篇
Day09 I'm watching you-UnderTaker,認識watch
下一篇
Day11 有背過元素週期表,那有看過元件生命週期圖嗎?
系列文
忍住不打牌位,只要30天VueJS帶你上A牌30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言