Vue
@unicep/vue gives you the useCep composable, for Vue 3.3 or newer.
npm install @unicep/vuepnpm add @unicep/vueyarn add @unicep/vuebun add @unicep/vue@unicep/core is installed with it.
<script setup lang="ts">import { ref } from 'vue';import { useCep } from '@unicep/vue';
const cep = ref('');const { data, error, isLoading } = useCep(cep);</script>
<template> <input v-model="cep" placeholder="00000-000" /> <p v-if="isLoading">Searching…</p> <p v-else-if="error">{{ error.message }}</p> <p v-else-if="data">{{ data.street }}, {{ data.neighborhood }} - {{ data.city }}/{{ data.state }}</p></template>The composable only looks up when the value is a valid CEP (with or without the hyphen), so you can wire it straight to a text field. If the CEP changes, the previous result is dropped and the in-flight request is cancelled.
useCep(cep: MaybeRefOrGetter<string | null | undefined>, options?: { unicep?: Unicep; // default: shared instance with all built-in providers enabled?: MaybeRefOrGetter<boolean>; // false pauses lookups, default true}): { data: Ref<Address | undefined>; error: Ref<Error | undefined>; isLoading: Ref<boolean>; // true while a lookup for the current valid CEP is in flight}cep and enabled accept a ref, a getter or a plain value. error is one of the
unicep errors, such as CepNotFoundError or AllProvidersFailedError.
Custom providers and options
Section titled “Custom providers and options”import { Unicep, viaCep, brasilApi } from '@unicep/core';
// Create it once, in a module, so you do not lose the circuit breaker state.const unicep = new Unicep({ providers: [viaCep(), brasilApi()], timeoutMs: 3000, cache: {},});
const { data } = useCep(cep, { unicep });