计算属性传参问题

版权声明:来自清心的博客 https://blog.csdn.net/jw2268136570/article/details/88732536
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报错,我们可以借助闭包外函数变量保活的特性来解决。

猜你喜欢

转载自blog.csdn.net/jw2268136570/article/details/88732536
今日推荐