目录
一、安装vuex
npm install vuex@next -S
npm install vuex-composition-helpers@next -S
二、使用多模块store配置
根目录创建store文件夹
1.先在module下创建app.ts
import { Module } from "vuex"
import { RootState } from "../index"
//定义类型
export interface appState {
test: string
}
export const store: Module<appState, RootState> = {
namespaced: true,
state: (): appState => ({
test: "app的statte",
}),
mutations: {
changeTest(state: appState, lang: string) {
state.test = lang
},
},
actions:{
test( store:any, value:any){
store.commit('changeTest',value)
}
}
}
2.创建index.ts
import { InjectionKey } from "@vue/runtime-core"
import { createStore, Store, useStore as baseUseStore } from "vuex"
import { store as app, appState } from "./module/app"
//定义RootState接口,将所有模块类型放入
export interface RootState {
app: appState
}
export const key: InjectionKey<Store<RootState>> = Symbol()
export const store: Store<RootState> = createStore({
modules: { app, },
})
export function useStore() {
return baseUseStore(key)
}
3.挂载在vue实例上
在main.ts中
import { createApp } from 'vue'
import App from './App.vue'
import ElementPlus from 'element-plus'
++import { store,key } from './store'
const app = createApp(App)
++app.use(store, key).use(ElementPlus, { size: 'small', zIndex: 3000 }).mount('#app')
至此结束配置
4.在逻辑页面ts文件中使用
<script lang="ts">
import { computed, defineComponent, onBeforeMount, ref } from 'vue'
++import { useStore } from '@/store/index'
const count = ref(0)
export default defineComponent ({
setup() {
++const store = useStore()
console.log("改变前",store.state.app.test )
++ store.dispatch('app/test',8888888)
console.log("改变后", store.state.app.test)
return {
}
}
})
</script>
效果:
本质用法同2.0一样,不一样的是使用ts需要对类型进行定义
特别注意在用dispatch的时候需要带上方法路径如:
store.dispatch('app/test',8888888)