【发布时间】:2022-07-16 06:26:46
【问题描述】:
从minimal Vue2+Vuex typescript app created with @vue/cli 开始。我想确保组件中对 this.$store.state 的引用是由 Vuex 存储及其模块声明的正确类型。
我怎样才能做到这一点?在没有干预的情况下,所有对this.$store 的引用都会解析为Store<any>。
在this commit 中,我将@vue/cli 创建的默认src/store/index.ts 更改为在商店中引入message 属性...
import Vue from "vue";
import Vuex from "vuex";
Vue.use(Vuex);
interface RootState {
message: string;
}
const state: RootState = {
message: "olleH",
};
export const store = new Vuex.Store({
state,
mutations: {},
actions: {},
modules: {},
});
在this commit 中,我将shims-vue.d.ts 更新为guidance online 之后的如下内容,以添加对Vue VM 的全局类型引用(我怀疑该方法仅适用于Vue3,因为本文档的URL 是next.vue ...)...
import type { HelloStore } from "./store";
declare module "*.vue" {
import Vue from "vue";
export default Vue;
}
declare module "@vue/runtime-core" {
interface ComponentCustomProperties {
$store: HelloStore;
}
}
尝试在 VSCode 中为 this.$store.state 获得自动完成支持仍然没有给我 message 属性。
我找不到任何关于如何在任何地方为 Vue2 实现这一点的指导。
我应该使用什么模式,以便this.$store 使用 Vuex3 在我的 Vue2 组件中正确输入。您无法使用这些工具的最新稳定版本获得正确键入的值,这似乎很疯狂。我错过了什么?
https://github.com/cefn/vuex-store-typing 的 repro 是我的参考案例,供任何想尝试的人参考。
【问题讨论】:
标签: typescript vue.js vuejs2 vuex store