前端方法通过return怎么赋值给变量啊

我想把接口返回的值直接return赋值给变量

img


created的时候赋值

img


打印出来是undefined

img



因为我之前也用return ,赋值能接收到的

img


img

img


前端代码写的不行,大伙凑合看。

想要执行函数就在外部看到结果 你就改成异步 因为函数在执行的时候还没有return呢 你就console 当然没有值

data里有参数的

img

  1. 可以再 request前面 就加个return

2.或者用一个变量接着。再retuen建议 第二种 。因为第一种 如果接口没请求成功返回的是 promise对象

getCount(){
let data;
  request.get().then((res)=>{
data=res.data;
 })
return data;
}

res属于函数内部变量,函数外面访问不到的


async getCount() {
   let { data } =  await request.get()
  return data 
}

使用 async 和await 或者直接返回一个promise

async getCount(gender){
    return await request().get().then((res)=>{
        return res
    })
},
async do(){
    this.male = await this.getCount(0)
},

题主 我平常都是这样写 可以试一下
如果你要在created里面调用 created前面也要加上async 然后再await this.getCount()
这是ES6的东西吧 异步请求就要等待
顺便说一句 我也是菜鸟 写的不好 不要见怪