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?