Typescript Vuex和vue属性装饰器与$store
我正在尝试在我的@组件上使用vuex$store。但它不是被动的:/ 例如:Typescript Vuex和vue属性装饰器与$store,typescript,vuejs2,vue-component,reactive-programming,vuex,Typescript,Vuejs2,Vue Component,Reactive Programming,Vuex,我正在尝试在我的@组件上使用vuex$store。但它不是被动的:/ 例如: import { Component, Vue } from 'vue-property-decorator'; @Component export default class Internationalize extends Vue { protected selectedLanguage: any = this.$store.getters['globalLocale']; priva
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);
}
}
}
这是.store.dispatch'updateLocale',newLanguage;
状态globalLanguages将更改,但我的变量selectedLanguage不是被动的
谢谢
编辑:很好
这是因为selectedLanguage不是计算属性/getter,因此它的值仅在实例化类时分配,而不是在稍后更新存储的GlobalScale时分配
第一种解决方案是简单地将selectedLanguage转换为组件本身中的计算属性,即getter:
protected get selectedLanguage() {
return this.$store.getters['globalLocale'];
}
或者,您也可以:
但是,这样做的问题是,在第二种解决方案中,您将失去类型安全性,如果愿意,您必须在组件本身中声明为selectedLanguage返回的类型,即:
@Component({
computed: {
...mapGetters({
selectedLanguage: 'globalLocale'
})
}
})
export default class Internationalize extends Vue {
protected selectedLanguage!: <YourTypeHere>
}
控制台中是否有任何错误
@Component({
computed: {
...mapGetters({
selectedLanguage: 'globalLocale'
})
}
})
@Component({
computed: {
...mapGetters({
selectedLanguage: 'globalLocale'
})
}
})
export default class Internationalize extends Vue {
protected selectedLanguage!: <YourTypeHere>
}