vue#toRefs TypeScript Examples

The following examples show how to use vue#toRefs. 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: store.ts    From vue3-treeview with MIT License 6 votes vote down vote up
export function createState(props: ITreeProps): string {
    const { nodes, config } = toRefs(props);

    const state: IState = {
        id: uniqueId(),
        nodes: computed(() => nodes.value),
        config: computed(() => config.value),
        focusable: ref(null),
        focusFunc: new Map<string, Function>(),
        dragged: ref({
            node: null,
            element: null,
            wrapper: null,
            parentId: null
        }),
    };
    states.set(state.id, state);

    return state.id;
}
Example #2
Source File: useIcon.ts    From vue3-treeview with MIT License 6 votes vote down vote up
export default function useIcon(props: Record<string, unknown>): {} {
    const { isLeaf } = toRefs(props); 
    
    const state = inject<IState>("state")

    const config = state.config;

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

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

    const hasIcons = computed(() => {
        return !isNil(closedIcon.value) && !isNil(openedIcon.value);
    });

    const useIcons = computed(() => {
        return !isLeaf.value && hasIcons.value;
    });

    const fakeNodeStyle = computed(() => {
        return {
            width: `${defaultSize}px`,
            height: `${defaultSize}px`
        };
    });

    return {
        hasIcons,
        openedIcon,
        closedIcon,
        useIcons,
        fakeNodeStyle
    };
}
Example #3
Source File: composable.ts    From vue-keycloak with Apache License 2.0 6 votes vote down vote up
useKeycloak = (): KeycloakComposable => {
  return {
    ...toRefs<KeycloakState>(state),
    keycloak: getKeycloak(),
    hasRoles: (roles: string[]) =>
      !isNil(roles) && state.isAuthenticated && roles.every(role => state.roles.includes(role)),
    hasResourceRoles: (roles: string[], resource: string) =>
      !isNil(roles) &&
      !isNil(resource) &&
      state.isAuthenticated &&
      roles.every(role => state.resourceRoles[resource].includes(role)),
  }
}
Example #4
Source File: useHistory.ts    From vhook with MIT License 6 votes vote down vote up
export function useHistory(): IHistoryResult {
  const state: UnwrapRef<IHistoryState> = reactive(buildState())
  const [, clearPopStateListener] = useEvent('popstate', buildState)
  const [, clearPushStateListener] = useEvent('pushstate' as any, buildState)
  const [, clearReplaceStateListener] = useEvent('replacestate' as any, buildState)
  const clear = () => {
    clearPopStateListener()
    clearPushStateListener()
    clearReplaceStateListener()
  }
  return {
    ...toRefs(state),
    clear
  }
}
Example #5
Source File: useCommon.ts    From vue3-treeview with MIT License 5 votes vote down vote up
export default function useCommon(props: INodeProps): IUseCommon {
    const { node } = toRefs(props);
    const state = inject<IState>("state");
    const config = state.config;
    const wrapper = ref<HTMLElement>(null);
    const focused = ref(false);

    const root = {
        emit: inject<(event: string, ...args: any[]) => void>("emitter")
    };

    ensureState(node.value);

    const hasNode = computed(() => {
        return !isNil(node);
    });

    const hasConfig = computed(() => {
        return !isNil(config.value);
    });

    const hasState = computed(() => {
        return hasNode.value && !isNil(node.value.state);
    });

    const disabled = computed(() => {
        return config.value.disabled || node.value.state.disabled;
    });

    const editable = computed(() => {
        return config.value.editable && 
        (!isNil(node.value.state.editable) ? node.value.state.editable : true) || defaultConfig.editable;
    });

    const editing = computed(() => {
        return editable.value && (config.value.editing === node.value.id);
    });

    const blur = ((e: MouseEvent) => {
        if (e.type === "blur") {
            const current = e.currentTarget as HTMLElement;
            const related = e.relatedTarget as HTMLElement;
    
            if (!current.contains(related)) {
                config.value.editing = null;
                focused.value = false;
                root.emit(nodeEvents.blur, e, node.value);
            }
        }
    });

    return {
        state,
        node, 
        config,
        hasNode,
        hasState,
        hasConfig,
        disabled,
        wrapper,
        editable,
        editing,
        focused,
        blur,
        root,
    };
}
Example #6
Source File: useStatus.ts    From nodestatus with MIT License 4 votes vote down vote up
useStatus = (props: Props) => {
  const { server } = toRefs(props);
  const getStatus = computed((): boolean => server.value.status.online4 || server.value.status.online6);

  const getLoad = computed((): number => parseLoad(server.value.status.load));

  const getCpuStatus = computed(
    (): number => (
      server.value.status.cpu === undefined
        ? 100
        : Math.round(server.value.status.cpu)
    )
  );

  const getNetworkProtocol = computed((): string => {
    if (server.value.status.online4 && server.value.status.online6) {
      return '双栈';
    }
    if (server.value.status.online4) {
      return 'IPv4';
    }
    if (server.value.status.online6) {
      return 'IPv6';
    }
    return '维护中';
  });

  const getRAMStatus = computed(
    (): number => (
      server.value.status.memory_total === undefined
        ? 100
        : Math.round(((server.value.status.memory_used / server.value.status.memory_total) * 100))
    )
  );

  const getHDDStatus = computed(
    (): number => (server.value.status.hdd_total === undefined
      ? 100
      : Math.round(((server.value.status.hdd_used / server.value.status.hdd_total) * 100))
    )
  );

  const getProcessBarStatus = computed(
    () => (data: number) => {
      if (data > 90) return 'error';
      if (data > 70) return 'warning';
      return 'success';
    }
  );

  const getUpTime = computed((): string => {
    if (getStatus.value) {
      const { uptime } = server.value.status;
      return parseUptime(uptime);
    }
    return '-';
  });

  const formatNetwork = computed(() => (data: number): string => {
    if (data < 1024) return `${data.toFixed(0)}B`;
    if (data < 1024 * 1024) return `${(data / 1024).toFixed(0)}K`;
    if (data < 1024 * 1024 * 1024) return `${(data / 1024 / 1024).toFixed(1)}M`;
    if (data < 1024 * 1024 * 1024 * 1024) return `${(data / 1024 / 1024 / 1024).toFixed(2)}G`;
    return `${(data / 1024 / 1024 / 1024 / 1024).toFixed(2)}T`;
  });

  const formatByte = computed(() => (data: number): string => {
    if (data < 1024) return `${data.toFixed(0)} B`;
    if (data < 1024 * 1024) return `${(data / 1024).toFixed(2)} KiB`;
    if (data < 1024 * 1024 * 1024) return `${(data / 1024 / 1024).toFixed(2)} MiB`;
    if (data < 1024 * 1024 * 1024 * 1024) return `${(data / 1024 / 1024 / 1024).toFixed(2)} GiB`;
    return `${(data / 1024 / 1024 / 1024 / 1024).toFixed(2)} TiB`;
  });

  return {
    getStatus,
    getNetworkProtocol,
    getLoad,
    getCpuStatus,
    getRAMStatus,
    getHDDStatus,
    getProcessBarStatus,
    getUpTime,
    formatNetwork,
    formatByte
  };
}
Example #7
Source File: useParam.ts    From jz-gantt with MIT License 4 votes vote down vote up
export function useInitParam(props: any, slots: Readonly<Slots>) {
  const { setHeaders } = useSetGanttHeader();
  const { GtParam } = useParamObject();
  const {
    showCheckbox,
    showExpand,
    headerHeight,
    levelColor,
    dark,
    ganttColumnSize,
    showToday,
    showWeekend,
    headerStyle,
    bodyStyle,
    rowHeight
  } = toRefs(props);

  function saveParams(init = false) {
    GtParam.showCheckbox = showCheckbox.value;
    GtParam.showExpand = showExpand.value;
    GtParam.headerHeight = parseNumber(headerHeight.value);
    GtParam.levelColor = levelColor.value;
    GtParam.dark = dark.value;

    const opts = {
      [Variables.key.showToday]: showToday.value,
      [Variables.key.showWeekend]: showWeekend.value,
      [Variables.key.header]: headerStyle.value || {},
      [Variables.key.body]: bodyStyle.value || {},
      [Variables.key.columnSize]: ganttColumnSize.value
    };

    if (init) {
      GtParam.rowHeight = parseNumber(rowHeight.value);

      GtParam.init({
        colSize: ganttColumnSize.value,
        rowHeight: rowHeight.value ?? Variables.size.defaultContentRowHeight
      });
    }

    GtParam.setGanttOptions(opts);
  }

  // 处理 slot 组件
  if (slots?.default) GtParam.setNodes(slots.default());

  // 接收命名组件
  // eslint-disable-next-line no-restricted-syntax
  for (const name in Variables.slots) {
    if (slots?.[name]) GtParam.addSlot(name, slots?.[name]);
  }

  // 保存其他参数
  saveParams(true);

  // 监听以下参数发生变化时重新保存参数内容
  watch(
    () => [
      props.bodyStyle,
      props.borderColor,
      props.primaryColor,
      props.levelColor,
      props.showCheckbox,
      props.showExpand,
      props.headerHeight,
      props.ganttColumnSize,
      props.showToday,
      props.showWeekend,
      props.headerStyle,
      props.bodyStyle,
      props.dark
    ],
    () => {
      saveParams();
    }
  );

  watch(
    () => [GtParam.headerUnit, props.rowHeight],
    () => {
      saveParams(true);
    }
  );

  watch(
    () => [GtParam.headerUnit, GtParam.ganttOptions.columnSize],
    () => {
      setHeaders();
    }
  );
}
Example #8
Source File: watch.ts    From theila with Mozilla Public License 2.0 4 votes vote down vote up
// setup is meant to be called from the component setup method
  // and provides seamless integration with the reactive properties of the component.
  public setup(props: any, componentContext: any) {
    const {
      resource,
      context,
      kubernetes,
      talos,
      theila,
      compareFn,
    } = toRefs(props);

    watch([
      resource,
      context,
      kubernetes,
      talos,
      theila,
      compareFn,
      ctx.current,
    ], (val, oldVal) => {
      if(JSON.stringify(val) != JSON.stringify(oldVal)) {
        startWatch();
      }
    });

    const startWatch = async () => {
      stopWatch();

      if(!resource.value) {
        return;
      }

      let source:Runtime;

      if(kubernetes.value) {
        source = Runtime.Kubernetes;
      } else if(talos.value) {
        source = Runtime.Talos;
      }  else if(theila.value) {
        source = Runtime.Theila;
      }
      else {
        throw new Error("unknown source specified");
      }

      const compare = compareFn && compareFn.value ? compareFn.value : defaultCompareFunc(this);
      const c = {};

      if(context && context.value) {
        Object.assign(c, context.value)
      }

      // override the context name by the current default one unless it's explicitly defined
      if(!componentContext.context || !componentContext.context.name)
        c["name"] = contextName();

      await this.start(
        source,
        resource.value,
        c,
        compare,
      );
    };

    const stopWatch = async () => {
      if(this.running.value) {
        await this.stop();
      }
    };

    const handleReconnect = async () => {
      await startWatch();
    }

    onMounted(async () => {
      ctx.api.addListener(ClientReconnected, handleReconnect);

      await startWatch();
    });

    onUnmounted(async () => {
      ctx.api.removeListener(ClientReconnected, handleReconnect);

      await stopWatch();
    });
  }