美文网首页
isReactive 和 isReadonly

isReactive 和 isReadonly

作者: sweetBoy_9126 | 来源:发表于2024-03-16 13:02 被阅读0次
    • reactive.spec.ts
    import { isReactive, reactive } from "../reactive"
    describe("reactive", () => {
      it("happy path", () => {
        const original = {foo: 1}
        const observed = reactive(original)
        expect(observed).not.toBe(original)
        expect(observed.foo).toBe(1)
    +    expect(isReactive(observed)).toBe(true)
    +    expect(isReactive(original)).toBe(false)
      })
    })
    
    • reactive.ts
    export const enum ReactiveFlags {
      IS_REACTIVE = '_v_isReactive'
    }
    export function isReactive(value) {
      // 这里之所以要取反是因为不是 reactive 不会走 baseHandlers 里的 createGetter
      return !!value[ReactiveFlags.IS_REACTIVE]
    }
    
    • baseHandlers.ts
    function createGetter(isReadonly = false) {
      return function get(target, key) {
        console.log(key)
        if (key === ReactiveFlags.IS_REACTIVE) {
          return !isReadonly
        }
          const res = Reflect.get(target, key)
          if (!isReadonly) {
            track(target, key)
          }
          return res
        }
    }
    

    isReadonly

    export const enum ReactiveFlags {
      IS_READONLY = '_v_isReadonly'
    }
    export function isReadonly(value) {
      return !!value[ReactiveFlags.IS_READONLY]
    }
    
    describe("readonly", () => {
      it("should make nested values readonly", () => {
        const original = {foo: 1, bar: {baz: 2}}
        const wrapped = readonly(original)
        expect(isReadonly(wrapped)).toBe(true)
      })
    
    function createGetter(isReadonly = false) {
      return function get(target, key) {
        console.log(key)
        if (key === ReactiveFlags.IS_REACTIVE) {
          return !isReadonly
        } else if (key === ReactiveFlags.IS_READONLY) {
          return isReadonly
        }
          const res = Reflect.get(target, key)
          if (!isReadonly) {
            track(target, key)
          }
          return res
        }
    }
    

    相关文章

      网友评论

          本文标题:isReactive 和 isReadonly

          本文链接:https://www.haomeiwen.com/subject/ywenzdtx.html