(no title)
quabity | 5 years ago
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.
No comments yet.