Contents

一、isReactive

检查一个对象是否是由 reactive() 或 shallowReactive() 创建的代理

  • 基本使用
1isReactive(reactive({}))            // => true
2isReactive(readonly(reactive({})))  // => true
3isReactive(ref({}).value)           // => true
4isReactive(readonly(ref({})).value) // => true
5isReactive(ref(true))               // => false
6isReactive(shallowRef({}).value)    // => false
7isReactive(shallowReactive({}))     // => true

 

  • 实现原理 (packages/reactivity/src/reactive.ts)

首先检查 value 是否为只读对象(通过调用 isReadonly 函数)

如果 value 是只读的,则递归地检查其原始对象(通过 __v_raw)是否为响应式对象

如果 value 不是只读的,则直接检查其 __v_isReactive 属性来判断其是否为响应式对象

1export enum ReactiveFlags {
2  SKIP = '__v_skip',
3  IS_REACTIVE = '__v_isReactive',
4  IS_READONLY = '__v_isReadonly',
5  IS_SHALLOW = '__v_isShallow',
6  RAW = '__v_raw',
7}
8
9/**
10 * Checks if an object is a proxy created by {@link reactive()} or
11 * {@link shallowReactive()} (or {@link ref()} in some cases).
12 *
13 * @example
14 * ```js
15 * isReactive(reactive({}))            // => true
16 * isReactive(readonly(reactive({})))  // => true
17 * isReactive(ref({}).value)           // => true
18 * isReactive(readonly(ref({})).value) // => true
19 * isReactive(ref(true))               // => false
20 * isReactive(shallowRef({}).value)    // => false
21 * isReactive(shallowReactive({}))     // => true
22 * ```
23 *
24 * @param value - The value to check.
25 * @see {@link https://vuejs.org/api/reactivity-utilities.html#isreactive}
26 */
27export function isReactive(value: unknown): boolean {
28  if (isReadonly(value)) {
29    return isReactive((value as Target)[ReactiveFlags.RAW])
30  }
31  return !!(value && (value as Target)[ReactiveFlags.IS_REACTIVE])
32}

 

二、其他

学习的记录,仅供参考