getter方法的作用 vuex_vue.js – Vuex – 何时使用getter以及何时使用state

Vuex getters是Vue计算的,因为Vuex状态是Vue数据.

场景1

In an action or getter, if you use a list of products multiple times to find a result would you then use getters.products or state.products?

我不太明白你的情况;代码示例可以更好地说明您的意思.

假设您有产品状态,这是一个产品对象数组.如果您需要访问多个地方的已排序(例如)产品,那么生成sortedProducts getter会比每次排序产品更好,因为Vue将缓存结果并且仅在产品数组更改时重新计算其值.

Also, if you needed to use the products 10 times in the same function, would you call getters.products or state.products 10 times or would you assign the products to a variable at the beginning and then use that 10 times? Are there any perfomance gain in any over the others?

如果您关注性能,则无需在函数开头将其分配给变量.访问商店状态或获取者的性能成本可以忽略不计.代码可读性在这里更重要.

情景2

sortedProducts getter函数不返回函数,因此Vuex将缓存结果.

Would it be better to have a state instead that is manually updated by an action and mutation?

如果你在谈论你的sortedProducts getter,没有.

Generally, would it ever make sense to have getters returning functions that has to do with large amount of data?

您需要getter返回函数的唯一情况是,您希望getter能够接受参数,在这种情况下,getter更像是Vue组件方法而不是Vue组件计算属性.

如果你有一个返回函数并处理大量数据的getter,那么Vuex无法帮助你缓存该函数调用的结果.你必须找到一种方法来最小化它被调用的次数,或者合并memoization等.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值