Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Vue 源码分析之 getValueByPath #6

Open
Jsmond2016 opened this issue Jul 4, 2021 · 0 comments
Open

Vue 源码分析之 getValueByPath #6

Jsmond2016 opened this issue Jul 4, 2021 · 0 comments

Comments

@Jsmond2016
Copy link
Owner

在 watch 的使用中,存在深度监听的场景,如:

data = {
 name: { firstName: 'xxx'}
}

watch: {

'name.firstName': function() {}

}

Vue 是如何通过传入的 name.firstName 找到对应的值的呢?

/** 原理 */
function getValue(data, path) {
  let paths = path.split('.')
  let res = data
  while (prop = paths.shift()) {
    res = res[prop]
  }
  return res
}

const data = {
  a: {
    b: {
      c: 'zzz'
    }
  }
}

// getValue(data, 'a.b.c')
console.log('getValue', getValue(data, 'a.b.c'));

/** 升级版,柯里化--使用闭包方式提升性能 */
function createGetValue(path) {
  let paths = path.split('.')

  return function getValue(data) {
    let res = data
    while (prop = paths.shift()) {
      res = res[prop]
    }
    return res
  }
}


const data2 = {
  a: {
    b: {
      c: 'zzz'
    }
  }
}
const fn = createGetValue('a.b.c')
const res = fn(data2)
console.log('createGetValue', res);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant