带有Typescript的Vuex存储类型
我正在尝试让Vuex商店对打字脚本友好。我正在按说明建造商店。但是,当我从组件访问带有Typescript的Vuex存储类型,typescript,vue.js,vuex,Typescript,Vue.js,Vuex,我正在尝试让Vuex商店对打字脚本友好。我正在按说明建造商店。但是,当我从组件访问this.$store时,类型为store 我不知道如何更改它,使其默认为存储,而无需每次强制转换。您可以在组件中声明属性,以便typescript应用键入。我一直用它来表示$refs,但它也适用于$store。您不需要对该属性执行任何操作,只需使用标记!操作员告诉传输程序vue将为您设置变量 $store!: Store<StoreStateType>; 别忘了从“vuex”导入存储、vuex状态类
this.$store
时,类型为store
我不知道如何更改它,使其默认为
存储
,而无需每次强制转换。您可以在组件中声明属性,以便typescript应用键入。我一直用它来表示$refs
,但它也适用于$store
。您不需要对该属性执行任何操作,只需使用标记!操作员告诉传输程序vue将为您设置变量
$store!: Store<StoreStateType>;
别忘了从“vuex”导入存储、vuex状态类和您使用的任何帮助程序
import{Store,mapState}
不幸的是,无法用更具体的类型覆盖VueX类型定义的存储
类型。我所能想到的最好办法是添加第二个字段,该字段返回$store
,但必须正确键入,这样您就不必到处使用强制转换,也不必在所有组件中声明它:
import { Store } from "vuex";
// Type the $tstore properly, which is the same as $store but properly typed.
// Unfortunately you cannot override the Store<any> type.
declare module "vue/types/vue" {
interface Vue {
$tstore: Store<State>;
}
}
// Set $tstore to be a getter that simply returns $store.
Object.defineProperty(Vue.prototype, "$tstore", {
get: function() {
return this.$store as Store<State>;
},
enumerable: true,
});
从“vuex”导入{Store};
//正确键入$tstore,与$store相同,但键入正确。
//很遗憾,您无法覆盖存储类型。
声明模块“vue/types/vue”{
接口Vue{
$t商店:商店;
}
}
//将$tstore设置为只返回$store的getter。
Object.defineProperty(Vue.prototype,“$tstore”{
get:function(){
将此.$store作为store返回;
},
可枚举:正确,
});
如果有人遇到这个问题-我们通过重新定义构造函数返回的类型来解决这个问题-
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;
这样我们就可以正确地使用打字:
methods: {
sessionStarted(): Boolean | undefined {
return this.$store.state.sessionState?.session.started;
},
你知道有没有一种方法可以让键入与此一起工作。$store.getters?@maembe不幸的是,我不这么认为-你可能会对枚举和一些泛型产生真正的兴趣,但这感觉比手动强制转换更糟糕=\
export default VueStrong.extend({
name: 'name',
components: {
componentA,
componentB,
},
methods: {
sessionStarted(): Boolean | undefined {
return this.$store.state.sessionState?.session.started;
},