最近写vuejs的时候,有这样一个需求,调用A接口,然后操作返回值,存到localstorage中;再调用B接口,然后操作返回值,存到localstorage中;最后跳转到另一个页面。
但是遇到了一个问题,在A接口还没有存数据到localstorage中时,页面已经执行了跳转操作。可以通过手动console.log验证执行顺序。
原先代码如下:
toHome (store_no) { //验证是否登录 this.verifyLogin(this); //获取店铺信息以及默认角色设置 apiGetStore(this, { store_no: store_no, sess_id: getStore('sess_id') }).then( res => { setStore('roles', this.roles); }); //获取店铺默认角色 apiGetStoreRole(this, { sess_id: getStore('sess_id') }).then( res => { setStore('default_roleId', res.data.id); }); //跳转供货首页 this.$router.push({ path: '/apply/index' }); }
这里总会在还没有存roles变量的时候,跳转到过后的页面,导致在跳转后的页面获取roles报错。
解决方法:
通过设置setTimeout延迟跳转时间强行解决,但是这个方法时间设置有问题,后期数据量大,接口回调执行时间过长没法兼容,强烈不推荐。
将下面的调用接口嵌套起来,大致代码如下:
toHome (store_no, type) { //验证是否登录 this.verifyLogin(this); //获取店铺信息以及默认角色设置 apiGetStore(this, { store_no: store_no, sess_id: getStore('sess_id') }).then( res => { //设置供货商分销商 setStore('rolesType', type); //获取店铺默认角色 apiGetStoreRole(this, { sess_id: getStore('sess_id') }).then( res => { this.$router.push({ path: this.goPath }); }); }); }
这里将B接口放在了A接口的回调里,同时将跳转放在了B接口的回调里。一层层嵌套起来后,就不会引起跳转页面比设置localstorage更快的问题。
分享这段代码是为了以后再遇到类似的问题的时候,都可以用这种思路解决,并不单单为了分享这个情况。