博文背景
{{ message }}
this.axios.get(‘xxx’).then(response=>(this.message=response.data))后面接箭头函数可以返回结果但是直接改成普通函数不可以返回结果
解决办法
<template>
<div id="app">
<!-- <img alt="Vue logo" src="./assets/logo.png">-->
<!-- <HelloWorld msg="Welcome to Your Vue.js App"/>-->
<pre>{{ info }}</pre>
</div>
</template>
<script>
// import HelloWorld from './components/HelloWorld.vue'
// import axios from "axios";
export default {
name: 'App',
// components: {
// HelloWorld
// },
// data() {
// return {
// message: "hello world"
// }
// }
// data: function() {
// return {
// message: "hello world"
// }
// }
data() {
return {
info: "waiting for api requesting"
}
},
// async mounted() {
// await this.axios.get('https://httpbin.org/get').then(response => JSON.stringify(this.info = response.data, null, 4))
// }
// 错误
async mounted() {
await this.axios.get('https://httpbin.org/get').then(function(response) {
console.log(response.data);
console.log(typeof(response.data))
return Promise.resolve(this.info=response.data["url"]);
})
}
}
// 正确
async mounted() {
let that=this;
await this.axios.get('https://httpbin.org/get').then(function(response) {
console.log(response.data);
console.log(typeof(response.data))
return Promise.resolve(that.info=response.data["url"]);
})
}
}
</script>
<style>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
font-size: 18px;
/*-moz-osx-font-smoothing: grayscale;*/
/*text-align: center;*/
color: #2c3e50;
/*margin-top: 60px;*/
}
</style>
Vue中Axios请求与数据绑定
本文介绍如何在Vue项目中使用Axios发起HTTP请求并正确处理响应数据。通过对比箭头函数与普通函数的不同用法,展示了如何将获取到的数据绑定到组件上,并给出了正确的实现方式。
130

被折叠的 条评论
为什么被折叠?



