typescript - 在 Typescript Vue2 组件中输入 this.$store

标签 typescript vue.js vuejs2 vuex store

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/

相关文章:

angular - 返回 false 而不是 undefined

typescript - VS Code 和 Yarn PnP

javascript - 开发过程中如何在VUE-CLI中启用控制台登录

javascript - 自定义指令 v-focus 在 Vue 应用程序中使用 v-show 输入

html - 为 bootstrap-vue 轮播图像添加背景颜色

javascript - 如何将 bool 对象转换为数组

vue.js - Vue,js如何计算两个输入值并将结果放入另一个输入字段?

javascript - 动态路由上的 Vue.js 2.0 转换未触发

vue.js - 没有 webpack/npm/yarn 的 Vue 组件

node.js - 编辑组件 html 时 Angular CLI 不会重新加载?