VUE3中的狀態管理VUEX
阿新 • • 發佈:2022-05-17
一、安裝
npm install vuex@next --save
或者
yarn add vuex@next --save
二、store檔案程式碼
src/store/index.ts
import { createStore, useStore as baseUseStore, Store } from 'vuex' import { InjectionKey } from 'vue' export interface State { count:number } export const key:InjectionKey<Store<State>> = Symbol('store') export const store = createStore<State>({ state: { count: 0 }, getters: { }, mutations: { }, actions: { }, modules: { } }) export function useStore () { return baseUseStore(key) }
三、$store 屬性的型別宣告
src目錄下建立vuex.d.ts
檔案
import { ComponentCustomProperties } from 'vue'
import { Store } from 'vuex'
import { State } from '@/store/index'
declare module '@vue/runtime-core' {
// 為 `this.$store` 提供型別宣告
interface ComponentCustomProperties {
$store: Store<State>
}
}
四、main.ts檔案
import { store, key } from './store'
const app = createApp(App)
app.use(store, key)
五、使用
<template> <div>{{$store.state.count}}</div> </template> <script lang="ts" setup> import { useStore } from '@/store/index' const store = useStore() console.log(store.state.count) </script>