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.js设计与实现》5.4 合理的触发响应 #333

Closed
jizai1125 opened this issue Sep 22, 2022 · 0 comments
Closed

《Vue.js设计与实现》5.4 合理的触发响应 #333

jizai1125 opened this issue Sep 22, 2022 · 0 comments

Comments

@jizai1125
Copy link

jizai1125 commented Sep 22, 2022

看源码时多了一种数组场景下的判断:不影响数组长度变化但是会触发副作用函数重新执行

const observed = reactive(new Array(3))
effect(() => {
  console.log(observed.length)
})
// 下面用例不会影响数组长度变化,不应该触发副作用函数重新执行
observed.x = 'x' // 非索引属性
observed[-1] = 'x'  // 负索引
observed[1] = 1  // 已存在索引

PR: fix(reactivity): add existing index or non-integer prop on Array should not trigger length dependency

源码

function createSetter(shallow = false) {
  return function set(
    target: object,
    key: string | symbol,
    value: unknown,
    receiver: object
  ): boolean {
    let oldValue = (target as any)[key]
   // 省略代码...
   
    const hadKey =
     // 新增判断
      isArray(target) && isIntegerKey(key)
        ? Number(key) < target.length
        : hasOwn(target, key)

    const result = Reflect.set(target, key, value, receiver)
    // don't trigger if target is something up in the prototype chain of original
    if (target === toRaw(receiver)) {
      if (!hadKey) {
        trigger(target, TriggerOpTypes.ADD, key, value)
      } else if (hasChanged(value, oldValue)) {
        trigger(target, TriggerOpTypes.SET, key, value, oldValue)
      }
    }
    return result
  }
}
@jizai1125 jizai1125 changed the title 《Vue.js设计与实现》5.4 合理的触发响应 - 新增内容 《Vue.js设计与实现》5.4 合理的触发响应 Sep 23, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant