在 Vuex 中基于状态属性进行计算的正确方法是什么? [英] What is the correct way to do calculations based on state properties in Vuex?

查看:31
本文介绍了在 Vuex 中基于状态属性进行计算的正确方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些相互依赖的 Vuex 属性,我想知道使用它们进行计算的最佳方法.

I have some Vuex properties that are dependent on each other and I would like to know the best way to do calculations with them.

例如

我的状态中有一个 fontSize 属性,其值为 16.

I have a fontSize property in my state that has a value of 16.

state: {
    fontSize: 16,
}

现在我还想要一个 lineHeight,它是通过将 fontSize 乘以 1.4 的因子来计算的.

Now I would also like to have a lineHeight that is calculated by multiplying the fontSize by a factor of 1.4.

所以我可以在我的吸气剂中说:

So I could say in my getters for example:

getters: {
   lineHeight: state => state.fontSize * 1.4
}

这是正确的做事方式还是我应该使用 Mixins/新的 Vue3 组合 API 而不是 Vuex 来进行这些类型的计算?

Is this the correct way of doing things or should I use Mixins / new Vue3 composition API instead of Vuex for these types of calculations?

推荐答案

是的,根据 官方文档 :

有时我们可能需要根据商店状态计算派生状态,例如过滤项目列表并对其进行计数

Sometimes we may need to compute derived state based on store state, for example filtering through a list of items and counting them

并且您还可以使用基于 fontSize 状态属性的名为 lineHeight 的计算属性:

and you could also use a computed property called lineHeight based on fontSize state property :

computed:{
   lineHeight(){
      this.$store.state.fontSize*1.4
   }

}

这篇关于在 Vuex 中基于状态属性进行计算的正确方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆