代码之家  ›  专栏  ›  技术社区  ›  zmbq

带有Typescript的Vuex存储类型

  •  7
  • zmbq  · 技术社区  · 6 年前

    我想让Vuex商店对打字友好。我正在按说明建商店 here . 但是,当我访问 this.$store 从组件中,类型为 Store<any>

    我不知道如何更改它,使其默认为 Store<MyState> 不需要每次都施法。

    1 回复  |  直到 6 年前
        1
  •  4
  •   user1518267    5 年前

    如果有人遇到这个问题-我们通过重新定义构造函数返回的类型来解决这个问题-

    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;
    

    然后我们就

    export default VueStrong.extend({
        name: 'name',
    
        components: {
            componentA,
            componentB,
    },
    

    这样我们就可以正确地使用打字:

    methods: {
    sessionStarted(): Boolean | undefined {
        return this.$store.state.sessionState?.session.started;
    },
    
        2
  •  3
  •   LPains    6 年前

    您可以在组件中声明一个属性,以便typescript应用类型。我用这个 $refs 一直都是,但它对 $store

    $store!: Store<StoreStateType>;
    

    我使用的另一种方法是使用 MapState MapGetters 组件辅助程序。它们为您创建属性,以便您可以在模板中使用它们。例子:

    @Component({
      computed: mapState({
        userFullName: (state: any) => state.user.fullName,
        userEmail: (state: any) => state.user.email
      })
    })
    

    import { Store, mapState } from "vuex"; .

        3
  •  2
  •   Timmmm    5 年前

    不幸的是,无法覆盖 Store<any> 由具有更特定类型的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,
    });