Recently, I attempted to utilize the Vue Composition API for global state management. For instance, I created a file named useLoading.js
to handle loading flags.
useLoading.js
import { reactive, toRefs } from '@vue/composition-api'
export default () => {
const state = reactive({
isLoading: false
})
const setIsLoading = (loading) => {
state.isLoading = loading
}
return {
...toRefs(state),
setIsLoading
}
}
Subsequently, I designed Component A, where the setIsLoading
function is triggered upon clicking a button.
ComponentA.vue
<template>
<div @click="showLoading" />
</template>
<script>
import useLoading from '@/composable/useLoading'
export default {
setup () {
const { setIsLoading } = useLoading()
function showLoading () {
setIsLoading(true)
}
return {
showLoading
}
}
}
</script>
In addition, there is also Component B which displays a <div>
based on the value of isLoading
being true
.
ComponentB.vue
<template>
<div v-if="isLoading" />
</template>
<script>
import useLoading from '@/composable/useLoading'
export default {
setup () {
const { isLoading } = useLoading()
return {
isLoading: isLoading
}
}
}
</script>
However, I encountered an issue where the value of isLoading
in ComponentB.vue
was not updating (non-reactive). Strangely, it did react to changes when manipulated in ComponentA.vue
.
I suspect that my implementation of using the Composition API as global state might be flawed. Any assistance would be greatly appreciated.
Thank you!