vue#ComputedRef TypeScript Examples

The following examples show how to use vue#ComputedRef. 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: utils.ts    From hexon with GNU General Public License v3.0 8 votes vote down vote up
export function useAsyncComponentWithLoading(
  loader: Parameters<typeof defineAsyncComponent>[0]
): [ReturnType<typeof defineAsyncComponent>, ComputedRef<boolean>] {
  const loading = ref(true)
  const _loader = "loader" in loader ? loader.loader : loader
  return [
    defineAsyncComponent(() =>
      _loader().then((res) => {
        loading.value = false
        return res
      })
    ),
    computed(() => loading.value),
  ]
}
Example #2
Source File: index.spec.ts    From vooks with MIT License 6 votes vote down vote up
describe('#use-breakpoint', () => {
  expectType<ComputedRef<'xs' | 's' | 'm' | 'l' | 'xl' | '2xl'>>(
    useBreakpoint()
  )
  expectType<ComputedRef<'xs' | undefined>>(useBreakpoint({ xs: 100 }))
  expectType<ComputedRef<'xs' | 's'>>(useBreakpoint({ xs: 0, s: 100 } as const))
  const ambigious: Record<string, number> = {}
  expectType<ComputedRef<string | undefined>>(useBreakpoint(ambigious))
})
Example #3
Source File: use-breakpoint.ts    From vooks with MIT License 6 votes vote down vote up
function useBreakpoint<T extends BreakpointOptions = DefaultBreakpointOptions> (
  screens?: T
): ComputedRef<ExtractBreakpoint<T> | undefined> {
  if (!isBrowser) return computed(() => undefined)
  // pass ts check
  const breakpointsRef =
    screens !== undefined ? useBreakpoints(screens) : useBreakpoints()
  return computed(() => {
    const { value } = breakpointsRef
    if (value.length === 0) return undefined
    return value[value.length - 1] as any
  })
}
Example #4
Source File: use-compitable.ts    From vooks with MIT License 6 votes vote down vote up
export default function useCompitable<T extends object, U extends Array<keyof T>, V extends keyof T> (
  reactive: T,
  keys: [...U, V]
): ComputedRef<T[V]> {
  // @ts-expect-error
  return computed(() => {
    for (const key of keys) {
      if (reactive[key] !== undefined) return reactive[key]
    }
    return reactive[keys[keys.length - 1]]
  })
}
Example #5
Source File: use-memo.ts    From vooks with MIT License 6 votes vote down vote up
function useMemo<T> (
  getterOrOptions: MemoGetter<T> | WritableMemoOptions<T>
): ComputedRef<T> | WritableComputedRef<T> {
  const computedValueRef = computed(getterOrOptions as any) as
    | WritableComputedRef<T>
    | ComputedRef<T>
  // Maybe it's not possible to lazy evaluate the value, since we can't make
  // render phase capture the deps behind useMemo
  const valueRef = ref(computedValueRef.value) as Ref<T>
  watch(computedValueRef, (value) => {
    valueRef.value = value
  })
  if (typeof getterOrOptions === 'function') {
    return valueRef as ComputedRef<T>
  } else {
    return ({
      __v_isRef: true,
      get value () {
        return valueRef.value
      },
      set value (v: T) {
        (getterOrOptions as WritableMemoOptions<T>).set(v)
      }
    } as unknown) as WritableComputedRef<T>
  }
}
Example #6
Source File: use-merged-state.ts    From vooks with MIT License 6 votes vote down vote up
export default function useMergedState<T> (
  controlledStateRef: Ref<T | undefined>,
  uncontrolledStateRef: Ref<T>
): ComputedRef<T> {
  watch(controlledStateRef, value => {
    if (value !== undefined) {
      uncontrolledStateRef.value = value
    }
  })
  return computed(() => {
    if (controlledStateRef.value === undefined) {
      return uncontrolledStateRef.value
    }
    return controlledStateRef.value
  })
}
Example #7
Source File: productsApi.ts    From master-frontend-lemoncode with MIT License 6 votes vote down vote up
useProductsApi = async (): Promise<{
  list: Ref<Product[]>
  totalProducts: ComputedRef<number>
}> => {
  const list: Ref<Product[]> = ref([])
  list.value = await productService.get()

  const totalProducts = computed(() => {
    return list.value.length
  })
  return { list, totalProducts }
}
Example #8
Source File: index.spec.ts    From vooks with MIT License 5 votes vote down vote up
describe('#use-breakpoints', () => {
  expectType<ComputedRef<Array<'xs' | 's' | 'm' | 'l' | 'xl' | '2xl'>>>(
    useBreakpoints()
  )
  expectType<ComputedRef<Array<'xs' | undefined>>>(useBreakpoints({ xs: 100 }))
})
Example #9
Source File: index.spec.ts    From vooks with MIT License 5 votes vote down vote up
describe('#use-compitable', () => {
  const x = { a: 1, b: undefined }
  expectType<ComputedRef<number>>(useCompitable(x, ['b', 'a']))
  expectType<ComputedRef<undefined>>(useCompitable(x, ['a', 'b']))
})
Example #10
Source File: use-breakpoints.ts    From vooks with MIT License 5 votes vote down vote up
function useBreakpoints<T extends BreakpointOptions> (
  screens: T = defaultBreakpointOptions as unknown as T
): ComputedRef<Array<ExtractBreakpoint<T>>> {
  if (!isBrowser) return computed(() => [])
  // eslint-disable-next-line @typescript-eslint/strict-boolean-expressions
  if (typeof window.matchMedia !== 'function') return computed(() => [])

  type BreakpointStatus = ExtractBreakpointStatus<T>

  const breakpointStatusRef = ref<BreakpointStatus>({} as BreakpointStatus)
  const breakpoints = Object.keys(screens)

  const updateBreakpoints: OnMqlChange = (e, breakpointName) => {
    if (e.matches) breakpointStatusRef.value[breakpointName] = true
    else breakpointStatusRef.value[breakpointName] = false
  }

  breakpoints.forEach((key) => {
    const breakpointValue = screens[key]
    let mql: MediaQueryList
    let cbs: Set<OnMqlChange>
    if (mqlMap[breakpointValue] === undefined) {
      mql = window.matchMedia(createMediaQuery(breakpointValue))
      // eslint-disable-next-line @typescript-eslint/strict-boolean-expressions
      if (mql.addEventListener) {
        mql.addEventListener('change', (e: MediaQueryListEvent) => {
          cbs.forEach((cb) => {
            cb(e, key)
          })
        })
        // eslint-disable-next-line @typescript-eslint/strict-boolean-expressions
      } else if (mql.addListener) {
        mql.addListener((e: MediaQueryListEvent) => {
          cbs.forEach((cb) => {
            cb(e, key)
          })
        })
      }

      cbs = new Set()
      mqlMap[breakpointValue] = {
        mql,
        cbs
      }
    } else {
      mql = mqlMap[breakpointValue].mql
      cbs = mqlMap[breakpointValue].cbs
    }
    cbs.add(updateBreakpoints)
    if (mql.matches) {
      cbs.forEach((cb) => {
        cb(mql, key)
      })
    }
  })

  onBeforeUnmount(() => {
    breakpoints.forEach((breakpoint) => {
      const { cbs } = mqlMap[screens[breakpoint]]
      if (cbs.has(updateBreakpoints)) {
        cbs.delete(updateBreakpoints)
      }
    })
  })

  return computed<Array<ExtractBreakpoint<T>>>(() => {
    const { value } = breakpointStatusRef
    return breakpoints.filter((key) => value[key]) as any
  })
}
Example #11
Source File: index.ts    From elenext with MIT License 5 votes vote down vote up
rowInjectKey: InjectionKey<{
  gutter: ComputedRef<GutterTuple>
}> = Symbol('Row')
Example #12
Source File: useData.ts    From jz-gantt with MIT License 5 votes vote down vote up
export function useInitData(
  data: Ref<Array<any>>,
  options: ComputedRef<DataOptions>
) {
  const store = useStore();
  const { GtData } = store;

  const { setHeaders } = useSetGanttHeader();
  const { IFClickRow } = useRootEmit();

  // 处理数据
  GtData.initData(data.value, options.value);

  const allData = computed(() => GtData.flatData as Row[]);

  // 监听数据变化
  watch(
    () => data,
    val => {
      let item = null as Row | null;

      // 先判断选中的内容
      const select = GtData.selected.index;
      if (select > -1) item = allData.value[select];

      GtData.update(val.value, item, options.value);
      setHeaders();

      // 数据发生变化,如果 selectIndex 变为 -1,表示数据已经被删除,选择的行内容需要抛出清空
      if (select > -1 && GtData.selected.index === -1) {
        IFClickRow(undefined);
      }
    },
    { deep: true }
  );

  return {
    allData
  };
}
Example #13
Source File: scope-element.ts    From quantum-sheet with GNU General Public License v3.0 5 votes vote down vote up
addVariable(name: string, position: ComputedRef<Vector2>): UseScopedVariable {
    // Add variable
    const variable: ScopedVariable = reactive({
      position: position,
      index: -1,
      data: shallowRef<any>(null),
      getters: [],
    })

    const variableArray = this.variableMap.get(name) ?? this.createVariableArray(name)

    watchImmediate(
      () => variable.position,
      (value) => {
        // Remove (or bail out)
        if (variable.index >= 0) {
          assert(variableArray[variable.index] == variable, `Expected variable ${variable} to be in ${variableArray} at index ${variable.index}`)

          const prev = arrayUtils.at(variableArray, variable.index - 1)
          const next = arrayUtils.at(variableArray, variable.index + 1)

          if (isInRange(value, { start: prev?.position, end: next?.position })) {
            // TODO: Optimize?
            // Currently this doesn't account for moving a variable past its getters
            // return
          }

          removeVariable(variableArray, variable)
        }

        // Add
        const { index } = arrayUtils.getBinaryInsertIndex(variableArray, (v) => v.position.compareTo(value))

        const prev = arrayUtils.at(variableArray, index - 1)
        // Take some getters from prev
        if (prev?.getters) {
          // Warning: This has to be strictly less than 0. If they are on the same spot, the getter belongs to the previous variable
          variable.getters = prev.getters.filter((v) => value.compareTo(v.position) < 0)
          variable.getters.forEach((v) => {
            v.variable = variable
          })
          prev.getters = prev.getters.filter((v) => !(value.compareTo(v.position) < 0))
        }
        // Update variable indices
        for (let i = index; i < variableArray.length; i++) {
          variableArray[i].index = i + 1
        }
        variableArray.splice(index, 0, variable)
        variable.index = index
      }
    )

    function setData(data: Expression | null | undefined) {
      variable.data = data
    }

    function remove() {
      removeVariable(variableArray, variable)
    }

    return {
      setData,
      remove,
    }
  }
Example #14
Source File: scope-element.ts    From quantum-sheet with GNU General Public License v3.0 5 votes vote down vote up
addGetter(name: string, position: ComputedRef<Vector2>): UseScopedGetter {
    const getter: ScopedGetter = reactive({
      position: position,
      variable: undefined,
    })
    const data = computed(() => getter.variable?.data)

    const variableArray = this.variableMap.get(name) ?? this.createVariableArray(name)

    watchImmediate(
      () => getter.position,
      (value) => {
        if (getter.variable) {
          // If the getter is still in the correct position, bail out
          const nextVariable = arrayUtils.at(variableArray, getter.variable.index + 1)
          if (
            isInRange(value, {
              start: getter.variable.position,
              end: nextVariable?.position,
            })
          ) {
            return
          }

          // Remove getter from old variable
          arrayUtils.remove(getter.variable.getters, getter)
          getter.variable = undefined
        }

        const { index } = arrayUtils.getBinaryInsertIndex(variableArray, (v) => v.position.compareTo(value))

        const variable = arrayUtils.at(variableArray, index - 1)
        assert(variable, `Getter position ${getter.position} outside of block ${this.position}`)

        // Add getter to variable
        variable.getters.push(getter)
        getter.variable = variable
      }
    )

    function remove() {
      if (!getter.variable) return
      arrayUtils.remove(getter.variable.getters, getter)
      getter.variable = undefined
    }

    return {
      data,
      remove,
    }
  }
Example #15
Source File: useCheckBox.ts    From vue3-treeview with MIT License 4 votes vote down vote up
export function useCheckBox(cmn: IUseCommon): {} {
    const node = cmn.node;
    const config = cmn.config;
    const nodes = cmn.state.nodes;

    const mode = computed(() => {
        return config.value.checkMode === checkMode.auto ? checkMode.auto : checkMode.manual;
    });

    const factory = computed(() =>  {
        return mode.value === checkMode.auto ? 
        auto(node, nodes) :
        manual(node);
    });

    watch(mode, (nv: number, ov: number) => {
        if (!eq(nv, ov)) {
            factory.value.rebuild();
        }
    });

    const checked = computed(() => {
        return factory.value.checked.value;
    });

    const indeterminate = computed(() => {
        return factory.value.indeterminate.value;
    });

    const hasCheckbox = computed(() => {
        return config.value.checkboxes || defaultConfig.checkboxes;        
    });

    const checkedClass = computed(() => {
        return [
            factory.value.checked.value ? config.value.checkedClass ? config.value.checkedClass : "checked" : null,
            factory.value.indeterminate.value ? config.value.indeterminateClass ? config.value.indeterminateClass : "indeterminate" : null
        ];
    });

    const allChecked = computed(() => {
        return factory.value.allChecked.value;    
    });

    const noneChecked = computed(() => {
        return factory.value.noneChecked.value;
    });

    const someChecked = computed(() => {
        return factory.value.someChecked.value;
    });

    const someIndeterminate = computed(() => {
        return factory.value.someIndeterminate.value;
    });

    watch<Array<ComputedRef>>([allChecked, noneChecked, someChecked], ([ov1, ov2, ov3]) => {
        if (ov1 || ov2 || ov3) {
            factory.value.updateState();
        }
    }, { deep: true });

    watch(someIndeterminate, (nv: boolean, ov: boolean) => {
        if (!eq(nv, ov)) {
            factory.value.updateState();
        }
    }, { deep: true });

    const clickCheckbox = (): void => {
        if (!cmn.disabled.value) {
            factory.value.click();
            factory.value.recurseDown(node.value);
            cmn.root.emit(checked.value ? checkboxEvents.checked : checkboxEvents.unchecked, node.value);
        }
    };

    const space = (() => {
        if (!cmn.editing.value && config.value.checkboxes && config.value.keyboardNavigation) {
            clickCheckbox();
        }
    });

    return {
        checked,
        hasCheckbox,
        indeterminate,
        checkedClass,
        space,
        clickCheckbox
    };
}