计算属性传参问题

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报错,我们可以借助闭包外函数变量保活的特性来解决。

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