vue#isRef TypeScript Examples

The following examples show how to use vue#isRef. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: util.ts    From vhook with MIT License 7 votes vote down vote up
export function getTarget(target: Target): EventTarget {
  if (typeof target === 'string') {
    const dom = document.querySelector(target)
    if (!dom && process.env.NODE_ENV !== 'production') {
      console.error('target is not found')
      throw Error(`target of selector ${target} is not found`)
    }
    return dom!
  }
  if (isRef(target)) {
    return target.value!
  }
  return target
}
Example #2
Source File: traverse.ts    From S2 with MIT License 6 votes vote down vote up
traverse = <T>(value: T, seen?: Set<T>) => {
  // eslint-disable-next-line dot-notation
  if (!isObject(value) || (value as any)['__v_skip']) {
    return value;
  }

  if (!isProxy(value) && !isRef(value)) {
    return value;
  }

  seen = seen || new Set();
  if (seen.has(value)) {
    return value;
  }
  seen.add(value);
  if (isRef(value)) {
    traverse(value.value, seen);
  } else if (isArray(value)) {
    for (let i = 0; i < value.length; i++) {
      traverse(value[i], seen);
    }
  } else if (isSet(value) || isMap(value)) {
    value.forEach((v: any) => {
      traverse(v, seen);
    });
  } else if (isPlainObject(value)) {
    for (const key in value as any) {
      traverse((value as any)[key], seen);
    }
  }
  return value;
}
Example #3
Source File: useRaw.ts    From formkit with MIT License 6 votes vote down vote up
/**
 * Gets the raw underlying target object from a Vue Ref or Reactive object.
 * @param obj - Get the underlying target object, or no-op.
 * @returns
 */
// eslint-disable-next-line @typescript-eslint/ban-types
export default function useRaw<T extends unknown>(obj: T): T {
  if (obj === null || typeof obj !== 'object') return obj
  if (isReactive(obj)) {
    obj = toRaw(obj)
  } else if (isRef(obj)) {
    obj = (isReactive(obj.value) ? useRaw(obj.value as T) : obj.value) as T
  }
  return obj
}
Example #4
Source File: watchVerbose.ts    From formkit with MIT License 6 votes vote down vote up
/**
 * "Touches" a given property for reactivity tracking purposes.
 * @param obj - A ref to traverse for a given path
 * @param path - An array of strings representing the path to locate
 * @returns
 */
function get(obj: unknown, path: string[]) {
  if (isRef(obj)) {
    if (path.length === 0) return obj.value
    obj = obj.value
  }
  return path.reduce((value, segment) => {
    if (value === invalidGet) return value
    if (value === null || typeof value !== 'object') {
      return invalidGet
    }
    return (value as any)[segment]
  }, obj)
}
Example #5
Source File: i18n.ts    From vue-i18n-next with MIT License 6 votes vote down vote up
function injectGlobalFields(app: App, composer: Composer): void {
  const i18n = Object.create(null)
  globalExportProps.forEach(prop => {
    const desc = Object.getOwnPropertyDescriptor(composer, prop)
    if (!desc) {
      throw createI18nError(I18nErrorCodes.UNEXPECTED_ERROR)
    }
    const wrap = isRef(desc.value) // check computed props
      ? {
          get() {
            return desc.value.value
          },
          // eslint-disable-next-line @typescript-eslint/no-explicit-any
          set(val: any) {
            desc.value.value = val
          }
        }
      : {
          get() {
            return desc.get && desc.get()
          }
        }
    Object.defineProperty(i18n, prop, wrap)
  })
  app.config.globalProperties.$i18n = i18n

  globalExportMethods.forEach(method => {
    const desc = Object.getOwnPropertyDescriptor(composer, method)
    if (!desc || !desc.value) {
      throw createI18nError(I18nErrorCodes.UNEXPECTED_ERROR)
    }
    Object.defineProperty(app.config.globalProperties, `$${method}`, desc)
  })
}
Example #6
Source File: vue.ts    From keen-slider with MIT License 6 votes vote down vote up
export function useKeenSlider<
  T extends HTMLElement,
  O = {},
  P = {},
  H extends string = KeenSliderHooks
>(
  options: Ref<KeenSliderOptions<O, P, H>> | KeenSliderOptions<O, P, H>,
  plugins?: KeenSliderPlugin<O, P, H>[]
): [Ref<T | undefined>, Ref<KeenSliderInstance<O, P, H> | undefined>] {
  const container = ref<T>()
  const slider = ref<KeenSliderInstance<O, P, H>>()

  if (isRef(options)) {
    watch(options, (newOptions, _) => {
      if (slider.value) slider.value.update(newOptions)
    })
  }

  onMounted(() => {
    if (container.value)
      slider.value = new KeenSlider<O, P, H>(
        container.value,
        isRef(options) ? options.value : options,
        plugins
      )
  })

  onUnmounted(() => {
    if (slider.value) slider.value.destroy()
  })

  return [container, slider]
}
Example #7
Source File: store.spec.ts    From vue3-treeview with MIT License 5 votes vote down vote up
test("Expect to create store", () => {
    const nodes = {
        id1: {
            text: "text1"
        }
    };

    const config = {
        roots: ["id1"]
    };

    const wrapper = mount({
        template: "<div></div>",
        props: ["nodes", "config"]
    }, {
        propsData: {
            nodes,
            config
        }
    });

    const id = createState(wrapper.props() as any);

    const state = states.get(id);

    expect(isRef(state.nodes)).toBe(true);
    expect(isReadonly(state.nodes)).toBe(true);
    expect(state.nodes.value.id1).toMatchObject({text: "text1"});
       
    expect(isRef(state.config)).toBe(true);
    expect(isReadonly(state.config)).toBe(true);
    expect(state.config.value).toMatchObject({roots:["id1"]});

    expect(isRef(state.focusable)).toBe(true);
    expect(state.focusable.value).toBeNull();

    expect(isRef(state.dragged)).toBe(true);
    expect(state.dragged.value).toMatchObject({
        node: null,
        element: null,
        wrapper: null,
        parentId: null
    });
});
Example #8
Source File: useTree.spec.ts    From vue3-treeview with MIT License 5 votes vote down vote up
describe("test useTree", () => {
    let useTest = null;

    let props = null;

    const fakeEmit = (evt: string, ...args: any[]) => {};

    const v = require("vue");

    v.onUnmounted = jest.fn();

    const spy = jest.spyOn(v, "provide").mockImplementation(() => () => {});

    beforeEach(() => {
        props = reactive({
            config: {
                root: ["id1"]
            },
            nodes: {
                id1: {
                    text: "test"
                }
            }
        });

        useTest = useTree(props, fakeEmit);
    });

    it("Expect to call provide", () => {
        expect(spy).toBeCalledWith("emitter", fakeEmit);
    });

    it("Expect to create element ref", () => {
        expect(isRef(useTest.element)).toBeTruthy();
        expect(useTest.element.value).toBeNull();
    });

    it("Expect to have basic style", () => {
        expect(useTest.style.value).toMatchObject({
            "align-items": "center",
            "display": "flex"
        });
    });
});
Example #9
Source File: watchVerbose.ts    From formkit with MIT License 5 votes vote down vote up
/**
 * Recursively retrieves all enumerable property paths from the origination
 * object. For example:
 * ```js
 * const obj = {
 *   a: {
 *     b: 123
 *   },
 *   c: 567
 * }
 * const paths = getPaths(obj)
 * // [
 * //   ['a'],
 * //   ['a', 'b'],
 * //   ['c']
 * // ]
 * ```
 * @param obj - An object to retrieve paths for.
 * @param parents - An array of parent paths.
 * @returns
 * @internal
 */
export function getPaths(
  obj: unknown,
  paths: Array<ObjectPath> = [],
  ...parents: string[]
): ObjectPath[] {
  if (obj === null) return paths
  if (!parents.length) {
    const path = Object.defineProperty([], '__str', {
      value: '',
    }) as unknown as ObjectPath
    obj = isRef(obj) ? obj.value : obj
    if (obj && typeof obj === 'object') {
      Object.defineProperty(path, '__deep', { value: true })
      paths.push(path)
    } else {
      return [path]
    }
  }
  if (obj === null || typeof obj !== 'object') return paths

  for (const key in obj) {
    const path = parents.concat(key) as ObjectPath
    Object.defineProperty(path, '__str', { value: path.join('.') })
    const value = (obj as Record<string, unknown>)[key]
    if (isPojo(value) || Array.isArray(value)) {
      paths.push(Object.defineProperty(path, '__deep', { value: true }))
      paths = paths.concat(getPaths(value, [], ...path))
    } else {
      paths.push(path)
    }
  }
  return paths
}
Example #10
Source File: useEvent.ts    From vhook with MIT License 5 votes vote down vote up
export function useEvent(
  event: string,
  cb: EventListenerOrEventListenerObject,
  options?: HandlerOptions,
  target: Target = window
) {
  if (!event || !cb) {
    return
  }
  let eventTarget: EventTarget | null = null
  function register() {
    eventTarget = registerEvent(target, event, cb, options)
  }
  function clear() {
    if (eventTarget) {
      eventTarget.removeEventListener(event, cb, options)
      eventTarget = null
    }
  }
  useLifecycles(
    () => {
      if (isRef(target)) {
        watchEffect(
          (onInvalidate) => {
            register()
            onInvalidate(() => {
              clear()
            })
          },
          { flush: 'sync' }
        )
      } else {
        register()
      }
    },
    () => {
      clear()
    }
  )
  const targetDom = {
    get value() {
      return eventTarget
    }
  }
  return [targetDom, clear]
}