Composables in Vue documentation demonstrate how small composition functions can be used for organizing code by composing the app.
Discover More About Extracting Composables for Code Organization
"Extracted composables act as component-scoped services that interact with each other."
When working with multiple composables, a common question arises: How can you communicate between them? Specifically, how do you modify a variable (ref) located within another composable? Imagine building an application with two composables - users and statistics. The challenge is altering the selectedUser
from within the loadStatistics
method with no direct access available. What approach should be taken to handle this situation effectively?
ShowStatistics.vue
<template>
<select v-model="selectedUser">
<option v-for="user in users" :value="selectedUser">
{{ user }}
</option>
</select>
<button @click="loadStatistics">
Load Statistics
</button>
</template>
<script setup lang="ts">
const { users, selectedUser } = useUsers()
const { loadStatistics } = useStatistics()
</script>
useUsers.ts
import { ref } from 'vue'
export function useUsers() {
const users = ref([])
const selectedUser = ref({})
users.value = UsersApi.getUsers()
return { users, selectedUser }
}
useStatistics.ts
export function useStatistics() {
const loadStatistics = () => {
window.store.statistics = StatisticsApi.loadStatistics()
selectedUser = window.store.statistics.user
// ^~~~~~~~~~~~~~~ ERROR: selectedUser is not defined
}
return { loadStatistics }
}