【问题标题】:Typing this.$store within a Typescript Vue2 component在 Typescript Vue2 组件中键入 this.$store
【发布时间】: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


    【解决方案1】:

    您在类型扩充中使用的模块名称为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
      }
    }
    

    【讨论】:

    • 我在github.com/vuejs/vuex/issues/994#issuecomment-1025004935 找到了一个总比没有好的解决方法,但这意味着我不能使用this.$store 并且必须继续将商店的内容“映射”到每个组件中,当我更喜欢直接使用存储状态而不是为每个组件所做的每个值的每次访问添加样板文件时。我认为导入store 的技术有同样的问题,对吧?假设我想在模板中引用存储内容,我必须不断将每个用法重新映射到 VM 中的本地命名属性。
    • 确实,如果经常需要重新映射会很不方便。在这种情况下,我会创建一个新的 Vue 全局属性,它使用所需的类型为 $store 起别名。这也将在模板中启用类型推断,只要您使用新的全局属性而不是 $store
    猜你喜欢
    • 2020-03-03
    • 2018-08-01
    • 2020-09-08
    • 2018-11-23
    • 2021-08-13
    • 1970-01-01
    • 1970-01-01
    • 2019-04-05
    • 2017-09-25
    相关资源
    最近更新 更多