目标

实现两个小工具函数,来判断是否为 响应性 对象和 只读对象

  1. it('isReactive', () => {
  2. const original = { foo: 1 };
  3. const observed = reactive(original);
  4. expect(isReactive(observed)).toBe(true);
  5. expect(isReactive(original)).toBe(false);
  6. });
  7. it('happy path', () => {
  8. const original = { foo: 1, bar: { baz: 2 } };
  9. const wrapped = readonly(original);
  10. expect(isReadonly(wrapped)).toBe(true);
  11. expect(isReadonly(original)).toBe(false);
  12. });

实现

因为在 baseHandlers 的 createGetter 中是有 isReadonly 的入参,所以只要想办法触发 get 就能知道是不是 reactive / readonly

  1. export enum ReactiveFlags {
  2. IS_REACTIVE = '__v_isReactive',
  3. IS_READONLY = '__v_isReadonly',
  4. }
  5. export function isReactive(value) {
  6. return !!value[ReactiveFlags.IS_REACTIVE];
  7. }
  8. export function isReadonly(value) {
  9. return !!value[ReactiveFlags.IS_READONLY];
  10. }
  1. import { ReactiveFlags } from './reactive';
  2. function createGetter(isReadonly = false) {
  3. return function get(target, key) {
  4. if (key === ReactiveFlags.IS_REACTIVE) {
  5. return !isReadonly;
  6. } else if (key === ReactiveFlags.IS_READONLY) {
  7. return isReadonly;
  8. }
  9. const res = Reflect.get(target, key);
  10. if (!isReadonly) {
  11. track(target, key);
  12. }
  13. return res;
  14. };
  15. }