从minimal Vue2+Vuex typescript app created with @vue/cli
开始。我想确保引用 this.$store.state
组件内的类型是由 Vuex 存储及其模块声明的正确类型。
我怎样才能实现这个目标?无需干预,所有对 this.$store
的引用解决 Store<any>
.
在 this commit我更改了默认src/store/index.ts
创建者 @vue/cli
介绍一个message
商店里的属性(property)...
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这是我为任何想尝试的人提供的引用案例。
最佳答案
您在类型增强中使用的模块名称是 Vue 3 only (代码略为 different in Vue 2 ),但对 $store
实例属性类型增强的支持仅为 added in Vuex 4 。这在 Vuex 3 中是不可能的。
但是,您实际上可以使用导出的 store
实例(已经 typed as HelloStore
)而不是 this.$store
,因为它们是同一个实例:
import store from '@/store' // store type is HelloStore
export default {
mounted() {
console.log(this.$store === store) // => true
}
}
关于typescript - 在 Typescript Vue2 组件中输入 this.$store,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70914546/