跳到主要內容

發表文章

Vue 3.0 reactive, computed 原始碼分析

Vue 3.0 reactive, computed 原始碼分析  此文件大量使用了程式碼,請善用 搜尋 ( Ctrl+F ) 來 trace 整段 code 在 Vue 3.0,computed 寫法也有所改變,寫法可以參考  Composition API ,裡面提供的例子如下 const state = reactive ( { count : 0 , double : computed ( ( ) => state . count * 2 ) } ) 讓我們用 Test Case 來看看 computed 可以做什麼事情 computed 可以傳入一個 function,function 裡面的值只要有改變,或是被給值,就會更新 computed 的回傳值中的 value。 以下面的例子來說,可以發現  computed(() => value.foo)  裡面用到了  value.foo ,所以當  value.foo = 1 時, cValue 中的  value  就會跟著更新為 1 it ( 'should return updated value' , ( ) => { const value = reactive < { foo ? : number } > ( { } ) const cValue = computed ( ( ) => value . foo ) expect ( cValue . value ) . toBe ( undefined ) value . foo = 1 expect ( cValue . value ) . toBe ( 1 ) } ) Computed 知道了 computed 的功能之後,讓我們來追一下原始碼是怎麼讓 computed 更新的,還有其中的奧妙之處。 首先我們直接看進去 computed 這個 function 的實作。以原先的 Test Case 來說,可以直接看到傳入的方法符合  getterOrOptions: (() => T) |