【问题标题】:Vue / Vuex. Vuex store properties not accessible from my componentVue/Vuex。我的组件无法访问 Vuex 存储属性
【发布时间】:2020-04-28 15:48:46
【问题描述】:

我有一个 vue 应用程序和一个组件。该组件已注册并渲染得很好。我刚刚导入了 vuex 来帮助进行状态管理。我正在使用 typescript 和 vue-class-decorator 以获得更好的类型安全性。

我的应用看起来像这样:.ts

// load vuex stores
let store = require('./store/store.ts');

// register components here...
Vue.component('my-component', require('./components/MyComponent.vue'));

// initialize vue applications here...
const app = new Vue({
    el: '#app',
    store
});

我可以 console.log 存储并查看存储确实是正确的。

这是我的商店:.ts

import Vuex from 'vuex'
import Vue from 'vue'

Vue.use(Vuex);

export default new Vuex.Store({
    state: {
        active: false,
    },
    getters: {
        isActive: state => state.active
    }
});

这是我的组件:.ts

import { Vue, Component, Prop } from 'vue-property-decorator'
import axios from 'axios'

@Component
export default class MyComponent extends Vue {

    @Prop(String) route?: string

    resent: boolean = false

    loading: boolean = false



    // constructor
    mounted (): void {
        if (!this.route) {
            throw new Error("The route property is missing");
        }
    }

    get myActiveState (this :Vue): any {
        console.log(this.$store);
        return this.$store.getters.isActive;
    }
}

我尝试什么都没关系,我无法访问 stores 状态属性。我可以控制台日志this.$store 并且我确实得到了正确的存储,如果我放一个断点并检查我可以直接访问活动属性,但是如果我尝试控制台日志this.store.state.activethis.store.getters.isActive,那么我得到一个错误。

[Vue warn]: Error in render: "TypeError: Cannot read property 'isActive' of undefined"

我可以设置一个断点并检查控制台以仔细检查每个属性的内容。一切看起来都很好。但是我无法使用$store.state.active 访问该物业,我必须使用$store.default.state.active

这是怎么回事?为什么我无法访问编码后的状态?另外尝试编码this.$store.default.state.active 给我一个构建错误property does not exist on type Store<any>

【问题讨论】:

  • 如果你登录 this.$store.getters 有一些内容?
  • 它没有。同样的错误。未找到吸气剂。 $store 很好,但 $store.getters 在运行时不存在。

标签: javascript vue.js vuejs2 vue-component vuex


【解决方案1】:

这家伙很好地解决了这个问题https://www.youtube.com/watch?v=V9MmoBAezD8

简而言之,您必须创建一个 shims-vuex.d.ts 来解决此问题,如 vuex v4.0.0 版本所述

State 类型将从您的store/index.ts 导出,它应该代表您的状态

import { State } from './store/index.ts';

declare module '@vue/runtime-core' {
  interface ComponentCustomProperties {
    $store: Store<State>;
  }
}

// Vuex@4.0.0-beta.1 is missing the typing for `useStore`. See https://github.com/vuejs/vuex/issues/1736
declare module 'vuex' {
  export function useStore(key?: string): Store<State>;
}

【讨论】:

    猜你喜欢
    • 2021-06-06
    • 2020-12-29
    • 2020-05-01
    • 2020-05-04
    • 1970-01-01
    • 2018-12-08
    • 1970-01-01
    • 2021-10-02
    • 2021-06-17
    相关资源
    最近更新 更多