Vue 3 is a progressive framework for web development, this opensource project is a power tool in web developer kit. It's fast, lightweight and easy to learn. Version 3 has many performance upgrade from Vue 2.
Vuex 4
Vuex 4 is the official store for managing global state in Vue 3 app. Setting up a JS store setup is so easy. Let's set up a store in TS, which require different approach
Add store to project
Fire the vue add vuex command from the root of the project, it will install the dependencies and create a blank store for us.
TS store
We need few interface, Injection keys to create and configure store. To simplify the store we can put everything in a single file , store.ts / index.ts.
// store.ts import { InjectionKey } from "vue"; import { createStore, Store } from "vuex"; export interface State { count: number; } export const key: InjectionKey<Store<State>> = Symbol(); export const store = createStore<State>({ state: { count: 1, }, mutations: { }, actions: { }, });
Global store configuration
To make the store available to all components, in the main.ts import and use the it as plugin.
import {store} from './store' const app = createApp(App) app.use(store).use(router).mount('#app')
In a component
In a component we can access the store using Vuex function, useStore.
<script setup lang="ts"> import {useStore} from 'vuex' const store = useStore(App); </script> <template> {{store.state.count}} </template>
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.