I had a similar misunderstanding when I first saw it, but globally declaring reactive variables and passing them around isn't really what it's about. Take, for example: https://github.com/antfu/vueuse/blob/master/packages/core/us.... Any component that wants to use a reactive reference to mouse coordinates can `const { x, y } = useMouse()` in `setup`, but `x` and `y` will refer to different objects in each of those components (since the `ref()` is instantiated inside the call to `useMouse()`). The functionality is what's shared between components, not the state/references.
That said, if you want to use the composition api to share state you can, and you can pretty easily set up some structure to restrict mutability:
// useStore.ts
import { reactive, readonly } from 'vue'
export const useStore = () => {
const state = reactive({ count: 0 })
const increment = (val = 1) => state.count += val
return {
state: readonly(state), // Readonly so state can't be mutated directly...
increment, // ...only through the mutations provided, like Vuex
}
}
// store.ts
import { useStore } from './useStore'
export const store = useStore() // Now components can share this instance
// MyCounter.vue
import { store } from './store'
export default {
setup: () => ({
count: store.state.count,
onClick: () => store.increment(5),
}),
}
Or you can just keep using Vuex for sharing state and use the composition API for sharing self-contained bits of functionality. Or, if nothing else, using the `setup` method instead of the Options API just gives you much more control over how you organize your own code within a component.
“’Cause the technology is just gonna get better and better and it’s gonna get easier and easier and more and more convenient and more and more pleasurable to sit alone with images on a screen given to us by people who do not love us but want our money. And that’s fine in low doses but if it’s the basic main staple of your diet you’re gonna die. In a meaningful way, you're going to die.” –David Foster Wallace
That said, if you want to use the composition api to share state you can, and you can pretty easily set up some structure to restrict mutability:
Or you can just keep using Vuex for sharing state and use the composition API for sharing self-contained bits of functionality. Or, if nothing else, using the `setup` method instead of the Options API just gives you much more control over how you organize your own code within a component.