computed
1.什麼計算屬性緩存
基礎使用:一樣是實現data
中數據的反轉表示,有如下兩種不一樣寫法,,顯然第一種比第二種結構簡潔和清晰,特別是在屢次使用的時候,template
裏面的代碼將更加混亂。函數
<p>Computed reversed message: "{{ reversedMessage }}"</p> <p>Computed reversed message: "{{message.split('').reverse().join('')}}"</p>
var vm = new Vue({ el: '#example', data: { message: 'Hello' }, computed: { reversedMessage: function () { // `this` points to the vm instance return this.message.split('').reverse().join('') }}})
使用場景:經過以上的使用咱們可知,在須要對數據進行復雜處理,且可能屢次使用的狀況下,儘可能採起計算屬性的方式。oop
特色:this
①使得數據處理結構清晰;lua
②依賴於數據,數據更新,處理結果自動更新;code
③計算屬性內部this
指向vm實例;對象
④在template
調用時,直接寫計算屬性名便可;get
⑤經常使用的是getter
方法,獲取數據,也可使用set
方法改變數據;原型
⑥相較於methods
,無論依賴的數據變不變,methods
都會從新計算,可是依賴數據不變的時候computed
從緩存中獲取,不會從新計算。string
2.computed原理
//初始化計算屬性 function initComputed (vm: Component, computed: Object) { const watchers = vm._computedWatchers = Object.create(null) for (const key in computed) { const userDef = computed[key] const getter = typeof userDef === 'function' ? userDef : userDef.get //經過watch爲計算屬性添加動態響應. watchers[key] = new Watcher(vm, getter, noop, computedWatcherOptions) //組件定義的計算屬性已經在組件原型上定義了。咱們只須要在這裏定義實例化的計算屬性。 if (!(key in vm)) { defineComputed(vm, key, userDef)}} } function defineComputed (target: any, key: string, userDef: Object | Function) { //userDef若是是函數類型,只有getter if (typeof userDef === 'function') { sharedPropertyDefinition.get = createComputedGetter(key) sharedPropertyDefinition.set = noop } else { //userDef若是是對象類型,可能存在getter或者setter sharedPropertyDefinition.get = userDef.get ? userDef.cache !== false ? createComputedGetter(key): userDef.get: noop sharedPropertyDefinition.set = userDef.set? userDef.set: noop} Object.defineProperty(target, key, sharedPropertyDefinition)} function createComputedGetter (key) { return function computedGetter () { const watcher = this._computedWatchers && this._computedWatchers[key] if (watcher) { if (watcher.dirty) { watcher.evaluate()} if (Dep.target) { watcher.depend()} return watcher.value}}}