【问题标题】:Vuex and vue-property-decorator reactivity with $storeVuex 和 vue-property-decorator 与 $store 的反应性
【发布时间】:2019-09-08 21:01:55
【问题描述】:

我正在尝试在我的@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;
        });
      }
    }
  }

【问题讨论】:

  • 您是否在控制台中遇到任何错误

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


【解决方案1】:

这是因为selectedLanguage 不是计算属性/getter,所以它的值仅在类实例化时分配,而不是在以后更新商店的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>
}

【讨论】:

    猜你喜欢
    • 2020-03-10
    • 1970-01-01
    • 2017-11-02
    • 2019-02-27
    • 2018-11-29
    • 2019-12-05
    • 2019-05-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多