Vuex和Vue-Property-Decorator与$ store的反应性

时间:2019-04-18 13:49:58

标签: typescript vuejs2 vue-component reactive-programming vuex

我正在尝试在我的@Component上使用vuex $ store。但是它不是被动的:/

示例:

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

  @Component
  export default class Internationalize extends Vue {

    protected selectedLanguage: any = this.$store.getters['globalLocale'];

    private langages = this.$store.getters['globalLanguages'];

    protected switchLanguage(locale: any) {
      if (locale !== this.selectedLanguage.locale) {
        const newLanguage = this.langages.find((lang: any) => lang.locale === locale);
        this.$store.dispatch('updateLocale', newLanguage);
      }
    }
  }

this.$store.dispatch('updateLocale', newLanguage); 状态globalLanguages将被更改,但是我的变量selectedLanguage没有反应。

谢谢

编辑:出色的工作

import { Component, Vue } from 'vue-property-decorator';
  import { mapGetters } from 'vuex';

  @Component({
    computed: {
      ...mapGetters({
        selectedLanguage: 'globalLocale',
        langages: 'globalLanguages'
      })
    }
  })
  export default class Internationalize extends Vue {

    protected selectedLanguage!: any;
    protected langages!: any;

    protected flag = this.$store.getters.globalLocale.flagSuffix;

    protected switchLanguage(locale: any) {
      if (locale !== this.selectedLanguage.locale) {
        const newLanguage = this.langages.find((lang: any) => lang.locale === locale);
        this.$store.dispatch('updateLocale', newLanguage).then(() => {
          this.$i18n.locale = locale;
          this.$i18n.setLocaleMessage(this.$i18n.locale, this.$store.getters.globalTranslations);
          this.$i18n.fallbackLocale = process.env.VUE_APP_DEFAULT_LOCALE;
        });
      }
    }
  }

1 个答案:

答案 0 :(得分:1)

这是因为selectedLanguage不是计算的属性/获取器,因此仅在实例化该类时才分配它的值,而不是在以后更新商店的globalLocale时才赋值。

第一种解决方案是简单地将selectedLanguage转换为组件本身的计算属性(即getter):

protected get selectedLanguage() {
    return this.$store.getters['globalLocale'];
}

或者,您也可以use mapGetters in the @Component decorator instead

@Component({
    computed: {
        ...mapGetters({
            selectedLanguage: 'globalLocale'
        })
    }
})

但是,这样做的问题是您在第二个解决方案中失去了类型安全性,并且,如果需要,您必须在组件本身中声明为selectedLanguage返回的类型,即:

@Component({
    computed: {
        ...mapGetters({
            selectedLanguage: 'globalLocale'
        })
    }
})
export default class Internationalize extends Vue {
    protected selectedLanguage!: <YourTypeHere>
}