計算屬性傳參問題

1.問題解決
  routeChildren: function (route) {
        return route.children.filter(function (child) {
          return !child.hidden
        })
    }

錯誤:局部變量route報錯undefined

  routeChildren: function (route) {
      return function (route) {
        return route.children.filter(function (child) {
          return !child.hidden
        })
      }
    }

正確:閉包保活

2.源碼解析
 if (typeof userDef === 'function') {
    sharedPropertyDefinition.get = shouldCache
      ? createComputedGetter(key)
      : createGetterInvoker(userDef)
    sharedPropertyDefinition.set = noop
  } 
  
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
    }
  }
}

綜上,我們可以粗略判斷:我們的function整個被賦值給了字段的get屬性。
這時我們傳的參數就容易出現undefined報錯,我們可以藉助閉包外函數變量保活的特性來解決。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章