How to use the @vue/composition-api.ref function in @vue/composition-api

To help you get started, we’ve selected a few @vue/composition-api examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github pikax / vue-composable / dist / vue-composable.es.js View on Github external
function useWebSocket(url, protocols) {
    const ws = new WebSocket(url, protocols);
    const messageEvent = ref(null);
    const errorEvent = ref();
    const data = ref(null);
    const isOpen = ref(false);
    const isClosed = ref(false);
    const errored = ref(false);
    /* istanbul ignore next  */
    let lastMessage = (process.env.NODE_ENV !== "production" && Date.now()) || undefined;
    ws.addEventListener("message", x => {
        messageEvent.value = x;
        data.value = x.data;
        // if the messages are to quick, we need to warn
        /* istanbul ignore else  */
        if (process.env.NODE_ENV !== "production") {
            if (Date.now() - lastMessage < 2) {
                console.warn('[useWebSocket] message rate is too high, if you are using "data" or "messageEvent"' +
                    " you might not get updated of all the messages." +
                    ' Use "ws..addEventListener("message", handler)" instead');
            }
github vuejs / vue-apollo / packages / vue-apollo-composable / src / useQuery.ts View on Github external
const vm = getCurrentInstance()
  const isServer = vm.$isServer

  if (variables == null) variables = ref()
  if (options == null) options = {}
  const documentRef = paramToRef(document)
  const variablesRef = paramToRef(variables)
  const optionsRef = paramToReactive(options)

  // Result
  /**
   * Result from the query
   */
  const result = ref()
  const resultEvent = useEventHook>()
  const error = ref(null)
  const errorEvent = useEventHook()

  // Loading

  /**
   * Indicates if a network request is pending
   */
  const loading = ref(false)
  trackQuery(loading)
  const networkStatus = ref()

  // SSR
  let firstResolve: Function
  let firstReject: Function
  onServerPrefetch(() => new Promise((resolve, reject) => {
    firstResolve = resolve
github dawg / vusic / src / base / ui.ts View on Github external
order?: number;
}

// FIXME(1) add function and that return a dispose function
// This should be added to the base later
const global: VueConstructor[] = [];
const statusBar: StatusBarItem[] = [];
// TODO introduce order
const activityBar: ActivityBarItem[] = [];
const panels: PanelItem[] = [];
const mainSection: VueConstructor[] = [];
const toolbar: ToolbarItem[] = [];
const trackContext: Array<{ text: string; callback: (index: number) => void; }> = [];
const openedSideTab = ref(undefined);
const openedPanel = ref(undefined);
const panelsSize = ref(250);
const sideBarSize = ref(250);
const rootClasses: string[] = [];

export const ui = {
  global,
  trackContext,
  statusBar,
  activityBar,
  panels,
  mainSection,
  toolbar,
  openedSideTab,
  openedPanel,
  panelsSize,
  sideBarSize,
  rootClasses,
github vuejs / vue-apollo / packages / vue-apollo-composable / src / useMutation.ts View on Github external
export function useMutation<
  TResult = any,
  TVariables = OperationVariables
> (
  document: DocumentNode | ReactiveFunction,
  options: UseMutationOptions | ReactiveFunction> = null,
) {
  if (!options) options = {}

  const loading = ref(false)
  trackMutation(loading)
  const error = ref(null)
  const called = ref(false)
  
  const doneEvent = useEventHook, Record>>()
  const errorEvent = useEventHook()

  // Apollo Client
  const { resolveClient } = useApolloClient()

  async function mutate (variables: TVariables = null, overrideOptions: Omit) {
    let currentDocument: DocumentNode
    if (typeof document === 'function') {
      currentDocument = document()
    } else {
      currentDocument = document
    }

    let currentOptions: UseMutationOptions
github vuejs / vue-apollo / packages / vue-apollo-composable / src / useQuery.ts View on Github external
const networkStatus = ref()

  // SSR
  let firstResolve: Function
  let firstReject: Function
  onServerPrefetch(() => new Promise((resolve, reject) => {
    firstResolve = resolve
    firstReject = reject
  }).then(stop).catch(stop))

  // Apollo Client
  const { resolveClient } = useApolloClient()

  // Query

  const query: Ref> = ref()
  let observer: Subscription
  let started = false

  /**
   * Starts watching the query
   */
  function start () {
    if (started || !isEnabled.value) return
    if (isServer && currentOptions.value.prefetch === false) return

    started = true
    loading.value = true

    const client = resolveClient(currentOptions.value.clientId)

    query.value = client.watchQuery({
github AlbertBrand / vue-async-function / tests / useAsync.spec.js View on Github external
it("sets mutually exclusive data or error", async () => {
    const promiseFn = () => Promise.resolve("done");
    const wrapPromiseFn = ref(promiseFn);
    const Component = createComponentWithUseAsync(wrapPromiseFn);

    const wrapper = shallowMount(Component);
    await wrapper.vm.$nextTick();

    expect(wrapper.vm.isLoading).toBe(false);
    expect(wrapper.vm.error).toBeUndefined();
    expect(wrapper.vm.data).toBe("done");

    wrapPromiseFn.value = () => Promise.reject("error");
    await flushPromises();

    expect(wrapper.vm.isLoading).toBe(false);
    expect(wrapper.vm.error).toBe("error");
    expect(wrapper.vm.data).toBeUndefined();
github davidkpiano / xstate / packages / xstate-vue / src / useService.ts View on Github external
export function useService(
  service:
    | Interpreter
    | Ref>
): {
  current: Ref>;
  send: Interpreter['send'];
  service: Ref>;
} {
  const serviceRef = isRef(service)
    ? service
    : ref>(service);
  const current = ref>(serviceRef.value.state);

  watch(serviceRef, (service, _, onCleanup) => {
    current.value = service.state;
    const { unsubscribe } = service.subscribe(state => {
      if (state.changed) {
        current.value = state;
      }
    });
    onCleanup(() => unsubscribe());
  });

  const send = (event: TEvent | TEvent['type']) => serviceRef.value.send(event);

  return {
    current,
github vuelidate / vuelidate / packages / docs / src / .vuepress / components / AsComposition.vue View on Github external
function usePassword ({ minimumLength }) {
  const password = ref('')
  const repeatPassword = ref('')

  const rules = {
    password: {
      required: withMessage('This field is required', required),
      minLength: withMessage(
        minLength(minimumLength),
        ({ $params }) => `Has to be at least ${$params.length} characters long`
      ),
      asyncValidator: withMessage(
        ({ $pending, $model }) => $pending ? 'Checking!' : `Error! ${$model} Isn’t "aaaa"`,
        asyncValidator
      ),
      $autoDirty: true
    },
    repeatPassword: {
      required,
github pikax / vue-composable / dist / vue-composable.es.js View on Github external
function usePromise(fn) {
    if (!fn) {
        throw new Error(`[usePromise] argument can't be '${fn}'`);
    }
    if (typeof fn !== "function") {
        throw new Error(`[usePromise] expects function, but received ${typeof fn}`);
    }
    const loading = ref(false);
    const error = ref(null);
    const result = ref(null);
    const promise = ref();
    const exec = async (...args) => {
        loading.value = true;
        error.value = null;
        result.value = null;
        const currentPromise = (promise.value = fn(...args));
        try {
            const r = await currentPromise;
            if (promise.value === currentPromise) {
                result.value = r;
            }
            return r;
        }
        catch (er) {
            if (promise.value === currentPromise) {
                error.value = er;
github pikax / vue-composable / dist / vue-composable.cjs.js View on Github external
function useRetry(options, factory) {
    const opt = !options || isFunction(options) ? {} : options;
    const fn = isFunction(options) ? options : factory;
    if (!isFunction(options) && !isObject(options)) {
        throw new Error("[useRetry] options needs to be 'object'");
    }
    if (!!fn && !isFunction(fn)) {
        throw new Error("[useRetry] factory needs to be 'function'");
    }
    const isRetrying = compositionApi.ref(false);
    const nextRetry = compositionApi.ref();
    const retryErrors = compositionApi.ref([]);
    const cancellationToken = { value: false };
    const retryId = { value: 0 };
    const retryCount = compositionApi.computed(() => retryErrors.value.length);
    const context = {
        isRetrying,
        retryCount,
        nextRetry,
        retryErrors,
        [ExecutionId]: retryId,
        [CancellationToken]: cancellationToken
    };
    const exec = fn
        ? (...args) => {
            ++context[ExecutionId].value;
            return defaultStrategy(opt, context, fn, args);