前提总结
vue3中使用ts简化useStore并且想要返回类型化的store,mian.ts同样需要引用并且使用key值,简化的只是vue文件中使用store时不需要引用\使用key值官网中并没有说明这一点,踩了一上午的坑终于解决了~
const app = createApp(App);
app.use(store, key).mount('#app');
详细步骤
当使用组合式 API 编写 Vue 组件时,您可能希望 useStore 返回类型化的 store。
[重点] mian.ts中无论如何都要使用key值
main.ts
import { store, key } from '@/store';
const app = createApp(App);
app.use(store, key).mount('#app');
store/index.ts中自定义useStore方法
store/index.ts
import { InjectionKey } from 'vue';
import { createStore, useStore as baseUseStore, Store } from 'vuex';
export interface State {
count: number
}
export const key: InjectionKey<Store<State>> = Symbol();
export const store = createStore<State>({
state: {
count: 0,
},
mutations: {
},
actions: {
},
modules: {
},
});
/**
* 这里本应该返回State的所有类型,暂用unknown代替
* @returns Store<State>
*/
export function useStore(): Store<unknown> {
return baseUseStore(key);
}
vue文件中使用useStore(此处只粘贴script部分)
<script lang='ts'>
import { defineComponent } from 'vue';
import { useStore } from '@/store';
export default defineComponent({
setup() {
const store = useStore();
console.log(store);
return {};
},
});
</script>
在浏览器中可以看到我们打印的store,到这一步就OK了!
回到我们的store/index.ts文件中,大家还记得我们的返回类型使用的是unknown吗,现在我们应该来完善一下
export function useStore(): Store<unknown> {
return baseUseStore(key);
}
不过为了方便理解,这里引用一下GitHub上一位大佬写的,做个示例.
可以看到最终导出的Store使用的是大佬自己写的type Store,有兴趣的可以点这里跳转去GitHub详细地看一下这个项目
import { store as app, AppStore, AppState } from '@/store/modules/app'
import { store as settings, SettingStore, SettingsState } from '@/store/modules/settings'
import { store as permission, PermissionStore, PermissionState } from '@/store/modules/permission'
import { store as user, UserStore, UserState } from '@/store/modules/user'
import { store as tagViews, TagsStore, TagsViewState } from '@/store/modules/tagsview'
export interface RootState {
app: AppState
settings: SettingsState
permission: PermissionState
user: UserState
tagViews: TagsViewState
}
export type Store = AppStore<Pick<RootState, 'app'>> & SettingStore<Pick<RootState, 'settings'>>
& PermissionStore<Pick<RootState, 'permission'>> & UserStore<Pick<RootState, 'user'>>
& TagsStore<Pick<RootState, 'tagViews'>>
export const store = createStore({
plugins,
modules: {
app,
settings,
permission,
user,
tagViews
}
})
export function useStore(): Store {
return store as Store
}