Home > Net >  How to communicate between Vue 3 composables?
How to communicate between Vue 3 composables?

Time:09-06

Vue docs describe how composables can be used for code organization by composing the app of small composition functions.

Extracting Composables for Code Organization

"You can think of these extracted composables as component-scoped services that can talk to one another."

But how do you communicate between these composables? How do I change a variable (ref) that is inside another composable. I am trying to build this app where I have 2 composables (users and statistics). And I need to change the selectedUser from inside the loadStatistics method. But I don't have access to the selectedUser from my Statistics composable. What is the best practice to do this?

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 }
}

CodePudding user response:

You can pass the selectedUser ref from useUsers() to useStatistics() as an argument:

ShowStatistics.vue:

<script setup lang="ts">
    const { users, selectedUser } = useUsers()
    const { loadStatistics } = useStatistics(selectedUser)
</script>

useStatistics.ts:

                                              
  • Related