vuex异步调用的takeLatest化(记一次项目中遇到的小问题)
- 前言: 第一次接触到takeLatest是在redux-saga, 包括takeLatest/takeEvery等
问题描述: 在一个有多级品类选择的页面 点击一个标签查询一次
后端接口在数据量比较大的情况下查询时间可能比较慢 并且接口的返回顺序不一定是前端页面调用的顺序
这个问题困扰了很久 解决办法有以下几种- 跟产品沟通,用户每选择一个品类,让用户手动点击查询按钮,并提供loading蒙层 使用户没法在数据未返回之前继续操作
- 前端参数hash化 将请求参数hash化 将页面所有请求的数据通过参数的hash值保存在store 通过getter得到本次hash对应的数据
以上两种方法 都很麻烦 第一个是需要更换用户体验 第二个会存储很多不需要的数据 且在特定场景下可能会造成性能问题
- 于是参考了redux-saga的takeLatest实现一下代码
代码如下
1 | export function takeLatest(action) { |
使用方式
1 | actions: { |
如果我不用vuex怎么办呢?
当然在页面上使用也是一样的 唯一不同的是在页面上我们需要考虑做下this的指向问题
1 | function takeLatest(action, cb) { |