VUE3中的状态管理VUEX
一、安装
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>