vue this生命周期

async mounted() {
    const data = await this.getTypeList().then(res => {
      return res
    })
    const typeId = data[0].id
    this.Blogselect(typeId)
},
methods: {
    getTypeList() {
      return new Promise((resolve, reject) => {
        typeApi.getList().then(res => {
          resolve(res.data)
        })
      })
    },
    Blogselect() {
    ....
    }
}

通过async 和await 更优雅的去处理一下,模拟同步主要是

因为http请求是异步事件,log事件是同步事件。js在执行时会将异步往后排,其实你的数据已经拿到了,只不过在这里打印不出来,如果放到你的请求完成函数中打印,就会打印出来结果了,这只是异步请求的问题,不是this的生命周期。。。

请求接口是异步,vue请求接口的操作建议放到created生命周期中

看你的意思是要先调用getTypeList接口拿到返回的数据之后再把返回数据当做参数去请求下一个接口,那么你可以将BlogSelect的调用写到getTypeList的.then回调中, 参考下边的代码

created(){
    this.getTypeList()
}

methods: {
    getTypeList(){
        typeApi.getList().then((res) => {
             const typeId = (res.data || [])[0].typeId
             this.BlogSelect(typeId);
        })
    },
    BlogSelect(typeId){
    }
}

 

二楼的写法没错,但是本来就是promise  没有必要在加一个啦

 

  • mounted() {
    },
    methods: {
        async getTypeList() {
          this.typeList = await typeApi.getList()
          if(this.typeList&&this.typeList.length){
            this.Blogselect(typeId)
          }
        },
        Blogselect(typeId) {
        ....
        }
    }

 

你看这样可以吗

 

请求接口是异步,要改成async,await同步阻塞就可以拿到数据了