How to use @vue/composition-api - 10 common examples

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 pikax / vue-composable / dist / vue-composable.cjs.js View on Github external
if (process.env.NODE_ENV !== "production") {
                    console.warn(`[pageSize] expected number but got: '${typeof v}' value: '${v}'`);
                }
                return;
            }
            _pageSize.value = v;
        }
    });
    const lastPage = compositionApi.computed(() => Math.ceil(total.value / pageSize.value));
    // make sure the current page is the correct value
    currentPage.value = _currentPage.value;
    const prev = () => --currentPage.value;
    const next = () => ++currentPage.value;
    const first = () => (currentPage.value = 1);
    const last = () => (currentPage.value = lastPage.value);
    compositionApi.watch([total, pageSize], () => {
        if (currentPage.value > lastPage.value) {
            currentPage.value = lastPage.value;
        }
    }, { lazy: true } // no need to run on first render
    );
    return {
        // Mutable state
        pageSize,
        total,
        currentPage,
        offset,
        // Computed
        lastPage,
        // Functions
        next,
        prev,
github metaspace2020 / metaspace / metaspace / webapp / src / components / RichText / RichTextArea.tsx View on Github external
]}
          style={`left: ${parent.menu.left}px; bottom: ${parent.menu.bottom}px`}
          onClick={(e: Event) => { e.preventDefault() /* Prevent form submission */ }}
        >
          {slots.default()}
        
      ) : <div>
  },
})

interface Props {
  content: string
  onUpdate: (content: string) =&gt; any
}

const RichTextArea = createComponent({
  props: {
    content: String,
    onUpdate: Function,
  },
  setup(props, { emit, slots }) {
    const state = reactive({
      editor: useEditor({
        content: props.content,
        onUpdate: (content) =&gt; emit('update', content),
      }),
    })

    const { editor } = state

    return () =&gt; (
      <div class="sm-RichText sm-RichTextArea relative"></div></div>
github logaretm / vue-use-web / src / LocalStorage.ts View on Github external
let initialized = false;

  // early init if possible.
  if (typeof window !== 'undefined') {
    init();
    initialized = true;
  }

  function handler(e: StorageEvent) {
    if (e.key === key) {
      value.value = e.newValue ? parseValue(e.newValue) : null;
    }
  }

  onMounted(() => {
    if (!initialized) {
      init();
    }

    window.addEventListener('storage', handler, true);
  });

  onUnmounted(() => {
    localStorage.setItem(key, JSON.stringify(value.value));
    window.removeEventListener('storage', handler);
  });

  return {
    value
  };
}
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&gt;()
  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(() =&gt; new Promise((resolve, reject) =&gt; {
    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&lt;{ text: string; callback: (index: number) =&gt; void; }&gt; = [];
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&lt;
  TResult = any,
  TVariables = OperationVariables
&gt; (
  document: DocumentNode | ReactiveFunction,
  options: UseMutationOptions | ReactiveFunction&gt; = null,
) {
  if (!options) options = {}

  const loading = ref(false)
  trackMutation(loading)
  const error = ref(null)
  const called = ref(false)
  
  const doneEvent = useEventHook, Record&gt;&gt;()
  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(() =&gt; new Promise((resolve, reject) =&gt; {
    firstResolve = resolve
    firstReject = reject
  }).then(stop).catch(stop))

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

  // Query

  const query: Ref&gt; = ref()
  let observer: Subscription
  let started = false

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

    started = true
    loading.value = true

    const client = resolveClient(currentOptions.value.clientId)

    query.value = client.watchQuery({
github posva / pinia / src / store.ts View on Github external
const storeWithState: Store = {
    id,
    // it is replaced below by a getter
    state: state.value,

    patch,
    subscribe,
    reset,
  }

  // @ts-ignore we have to build it
  const computedGetters: StoreGetters = {}
  for (const getterName in getters) {
    const method = getters[getterName]
    // @ts-ignore
    computedGetters[getterName] = computed&gt;(() =&gt;
      getters[getterName](state.value)
    )
  }

  const store = {
    ...storeWithState,
    ...computedGetters,
  }

  // make state access invisible
  Object.defineProperty(store, 'state', {
    get: () =&gt; state.value,
    set: (newState: S) =&gt; {
      isListening = false
      state.value = newState
      isListening = true
github dawg / vusic / src / modules / audio / transport.ts View on Github external
constructor() {
    // FIXME Maybe all of the clocks could share one "ticker"?? IDK? Then we wouldn't have to "watch" the BBM
    // Note, this will run automatically
    watch(Context.BPM, () => {
      this.clock.frequency.value = 1 / (60 / Context.BPM.value / Context.PPQ);
    });
  }