vue axios异步请求获取的数据通过return返回后为空

在视图里面调用函数getLocalCity1,得不到函数的返回值,该如何将值显示在这个p标签呢?
image.png
image.png
使用async/await也不行,有返回值,但是返回值放在页面上是promise对象
image.png
image.png
尝试在data里面加一个变量address来保存返回值,但是就会发生循环错误
image.png
image.png
image.png

阅读 8.6k
4 个回答

好好的异步被你用了个稀碎。

方案一: 同步的ajax,因为你是jsonp天生异步。
方案二:增加一个ip_jsonp_result字段,直接使用这个字段渲染,然后jsonp请求之后给这个变量赋值。

promise不能返回值,返回的还是promise对象, 要先resolve

return Promise.resolve(address);

补:

async getLocalCity1() {
    ……
    let address = await this.$jsonp(url, data).then(res => {
    ……
    return Promise.resolve(address);
  })
}

你应该 把 return 放在 await 前面

async/await 应该这样用吧。。。

async () => {

    const res = await this.$jsonp(...);
    // 在这里写 .then 里面的东西。处理 res
    // async/await 只是将写代码的方式由异步回调变为同步。。并不会改变代码的运行方式。
}

你可以试试这样处理

<template>
...
<p>{{showAddress || getLocalCity(参数)}}</p>
...
</template>
...
data() {
    return {
        // ...
        showAddress: undefined,
    }
},
methods: {
    //...
    async getLocalCity() {
        // ...
        const res = await this.$jsonp();
        // 通过 res 组合出来 address
        this.showAddress = '...'
    }
}

补充

<template>
...
<template slot-scope="scope">
<p>{{showAddresses[`k_{scope.$index}`] || getLocalCity(参数, scope.$index)}}</p>
</template>
...
</template>
...
data() {
    return {
        // ...
        showAddresses: {},
    }
},
methods: {
    //...
    async getLocalCity(参数, key) {
        // ...
        const res = await this.$jsonp();
        // 通过 res 组合出来 address
        this.showAddresses[key] = '...'
    }
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题