Contents

一、isReadonly

检查传入的值是否为只读对象

通过 readonly() 和 shallowReadonly() 创建的代理都是只读的,因为他们是没有 set 函数的 computed() ref

  • 基本使用
1// Create a readonly object
2console.log(isReadonly(readonly({ key: 'value' }))) // Output: true
3
4// Create a reactive object
5console.log(isReadonly(reactive({ key: 'value' }))) // Output: false
6
7// Create a shallowReadonly object
8console.log(isReadonly(shallowReadonly({ key: 'value' }))) // Output: true
9
10// Create a regular object
11console.log(isReadonly({ key: 'value' })) // Output: false

 

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

该函数直接检查 value 是否存在,并且是否有 __v_isReadonly 属性

如果存在 __v_isReadonly 属性,则说明该对象是通过 readonly 或 shallowReadonly 创建的,只读属性不能被直接修改

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 whether the passed value is a readonly object. The properties of a
11 * readonly object can change, but they can't be assigned directly via the
12 * passed object.
13 *
14 * The proxies created by {@link readonly()} and {@link shallowReadonly()} are
15 * both considered readonly, as is a computed ref without a set function.
16 *
17 * @param value - The value to check.
18 * @see {@link https://vuejs.org/api/reactivity-utilities.html#isreadonly}
19 */
20export function isReadonly(value: unknown): boolean {
21  return !!(value && (value as Target)[ReactiveFlags.IS_READONLY])
22}

 

二、其他

学习的记录,仅供参考