一、创建store文件夹下的index.ts
// index.ts
import {createStore,Store} from 'vuex'
import {InjectionKey} from 'vue'
export const key: InjectionKey<Store<state>> = Symbol('key')
export type state ={
count:number
}
export default createStore({
state:{
count:0
},
mutations:{
add(state){
state.count +=1
}
}
})
二、声明 类型文件
//vuex.d.ts
import {ComponentCustomProperties} from 'vue'
import {Store} from 'vuex'
import { state } from '../store'
declare module '@vue/runtime-core' {
interface ComponentCustomProperties {
$store : Store<state>
}
}
三、main.ts文件
import { createApp } from 'vue'
import App from './App.vue'
import Store,{key} from './store'
createApp(App).use(Store,key).mount('#app')
四、组件中使用
//模板中
<template>
<p>{{this.$store.state.count}}</p>
// 这里就可以直接使用 this.$store.state
</template>
<script lang="ts" setup>
import {computed} from 'vue
import {useStore} from 'vuex'
import {key} from '../store' //从store文件夹下的index中引入
const store = useStore(key)
// 在计算属性中使用
let counts = computed(()=>{
return store.state.count
})
// 方法中调用mutations
let run =()=>{
return store.commit('add')
}
</script>