使用 Typescript 的 Vuex 存储类型 [英] Vuex store type with Typescript

查看:27
本文介绍了使用 Typescript 的 Vuex 存储类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试让 Vuex 商店对 Typescript 友好.我正在按照此处的说明构建商店.但是,当我从组件访问 this.$store 时,类型为 Store .

I'm trying to get a Vuex store to be Typescript friendly. I'm building the store as explained here. However, when I access this.$store from a component, the type is Store<any> .

我不知道如何更改它以使其默认为 Store 而无需每次都进行强制转换.

I couldn't figure out how to change it so that it defaults to Store<MyState> without requiring a cast every time.

推荐答案

如果有人遇到这个问题 - 我们通过重新定义构造函数返回的类型来解决这个问题 -

If anyone comes across this - we got around this issue by redefining the type that the constructor returned -

import Vue, { VueConstructor } from 'vue'
import { Store } from 'vuex'
import { RootState } from '@/store/types'

abstract class VueStrongClass extends Vue {
    public $store!: Store<RootState>
}
const VueStrong = Vue as VueConstructor<VueStrongClass>;

export default VueStrong;

然后我们就

export default VueStrong.extend({
    name: 'name',

    components: {
        componentA,
        componentB,
},

这让我们可以正确使用打字:

which lets us then use typing properly:

methods: {
sessionStarted(): Boolean | undefined {
    return this.$store.state.sessionState?.session.started;
},

这篇关于使用 Typescript 的 Vuex 存储类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆