Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

306
Visualizações
Vue composable - how to use multiple instances of composable without sharing state?

I have a composable file in my VueJS application:

// simple example of a composable that fetch some information from API and shows that information 
// in a table in two components at the sime time
export function useDatatable () {
  const table = ref({
    headers: [...],
    items: [],
    someValue: ''
  })

  async function getDocuments () {
    const { data } = await $axios.get('/documents')
    table.value.items = data
  }

  return {
    table,
    getDocuments
  }
}

Then I have multiple components that use this composable at the same time:

<template>
  <div>
    <document-table /> // composable is used here
    <document-billing-dialog /> // composable is used here too
  </div>
</template>

Then in both components (document-table and document-billing-dialog) I use this composable like this:

<template>
  <div>
    {{ table.someValue }}
  </div>
  <v-table :items="table.items" />
  <v-btn @click="getDocuments">
    Reload table
  </v-btn>
  // other components
</template>

<script>
  import { useDatatable } from '~/composables/useDatatable'
  // other imports

  export default defineComponent({
    setup () {
      const { table, getDocuments } = useDatatable()

      onMounted(() => { getDocuments() })

      return {
        table,
        getDocuments
      }
    }
  })
</script>

However when 1 component calls the getDocuments function it gets called twice because its being used in two components at the same time.

Other example is that if I change the value of table.value.someValue = 'something' it changes in both components.

Is there any way to have multiple instances of a composable at the same time without sharing the state?

almost 4 years ago · Santiago Trujillo
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda