Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

312
Views
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
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!