vue.js - vue2.0 beforeRouteEnter里 怎么调两个接口

查看:447
本文介绍了vue.js - vue2.0 beforeRouteEnter里 怎么调两个接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

我想进入页面的时候调两个接口,但是都不能执行,写一个是可以执行,但是写两个不能执行

  beforeRouteEnter (to, from, next) {
    main._base({
      methodName: 'QueryProductInfo',
      productId: to.params.id
    }).then(resp => {
      next(vm => {
        vm.product = resp.data.product
        vm.shop = resp.data.shop
        console.log(vm.product)
        console.log(vm.shop)
      })
    })
    //如果只写一个是可以调用的
    main._base({
      methodName: 'QueryProductReview',
      type: '0',
      index: '0',
      count: '2',
      productId: to.params.id
    }).then(resp => {
      next(vm => {
        vm.evalData = resp.data
        console.log(vm.evalData)
      })
    })

哪位大侠可以告知 怎么写调两个吗

解决方案

next 只能調用一次,這邊可以用 Promise.all 解決,等待兩個異步操作都返回結果後再 next:

beforeRouteEnter (to, from, next) {
  // Promise.all 會等到數組內的 Promise 都 resolve 後才會繼續跑(then)
  Promise.all([
    main._base({
      methodName: 'QueryProductInfo',
      productId: to.params.id
    }),
    main._base({
      methodName: 'QueryProductReview',
      type: '0',
      index: '0',
      count: '2',
      productId: to.params.id
    })
  ])
  .then( result => next( vm => {
    // 執行結果會按照上面順序放在 result 數組內,所以 result[0],代表第一個函數的 resolve 結果
    vm.product = result[0].data.product
    vm.shop = result[0].data.shop

    vm.evalData = result[1].data
  }))
}

这篇关于vue.js - vue2.0 beforeRouteEnter里 怎么调两个接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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