shallowReactive为什么没有起效果?

新手上路,请多包涵

shallowReactive没有起效果,用isReactive输出person.name 理论上应该为true,请问是怎么回事


const person = shallowReactive({
  // 只将第一层数据做了响应式处理
  name: '张三',
  age: 18,
  likeFood: {
    fruits: {
      apple: '苹果' // 深层次的数据将会是一个普通的对象
    }
  }
})
onMounted(() => {
//输出后发现是两个false  只输出person为true
  console.log(
    isReactive(person.name),
    '...............',
    isReactive(person.likeFood)
  )
 
阅读 1.7k
1 个回答

官方例子:
https://cn.vuejs.org/api/reac...
person.name 只是一个字符串,不会是 Reactive 对象的
isReactive(person.name) 等价于 isReactive("张三")

源码的处理:

const res = Reflect.get(target, key, receiver)

if (isSymbol(key) ? builtInSymbols.has(key) : isNonTrackableKeys(key)) {
  return res
}

// 收集依赖
if (!isReadonly) {
  track(target, TrackOpTypes.GET, key)
}

// 浅层
if (shallow) {
  return res
}

if (isRef(res)) {
  // ref unwrapping - skip unwrap for Array + integer key.
  return targetIsArray && isIntegerKey(key) ? res : res.value
}

// 是对象,再次调用 reactive
if (isObject(res)) {
  // Convert returned value into a proxy as well. we do the isObject check
  // here to avoid invalid value warning. Also need to lazy access readonly
  // and reactive here to avoid circular dependency.
  return isReadonly ? readonly(res) : reactive(res)
}

return res
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题