Vue.js 处理axios.get在vue上的响应
我正在学习Vue教程,我不确定如何处理Vue.js 处理axios.get在vue上的响应,vue.js,axios,Vue.js,Axios,我正在学习Vue教程,我不确定如何处理axios。在不使用的情况下获得响应,然后使用等待 <script> // @ is an alias to /src import axios from 'axios'; export default { name: 'home', components: { }, data(){ return { fecha: '', maximo: new Date().toISOString().sub
axios。在不使用的情况下获得响应,然后使用等待
<script>
// @ is an alias to /src
import axios from 'axios';
export default {
name: 'home',
components: {
},
data(){
return {
fecha: '',
maximo: new Date().toISOString().substr(0, 10),
minimo: '1984',
resultado: null
}
},
methods:{
async getDolar(dia){
console.log(`https://mindicador.cl/api/dolar/${dia}`);
let resultado = await axios.get(`https://mindicador.cl/api/dolar/${dia}`);
return resultado;
}
},
created(){
let hoy = new Date().toISOString().substr(0, 10).split('-').reverse().join('-');
this.resultado = this.getDolar(hoy);
console.log(this.resultado)//it's a promise
}
}
</script>
//@是/src的别名
从“axios”导入axios;
导出默认值{
姓名:'家',
组成部分:{
},
数据(){
返回{
费查:“,
maximo:new Date().toISOString().substr(0,10),
小调:“1984”,
结果:空
}
},
方法:{
异步getDolar(直径){
console.log(`https://mindicador.cl/api/dolar/${dia}`);
让resultado=等待axios.get(`https://mindicador.cl/api/dolar/${dia}`);
返回resultado;
}
},
创建(){
让hoy=newdate().toISOString().substr(0,10).split('-').reverse().join('-');
this.resultado=this.getDolar(hoy);
console.log(this.resultado)//这是一个承诺
}
}
可以在没有的情况下获取json响应,然后??等待,对于任何承诺,您都可以使用等待来获取其值:
async created() {
let hoy = new Date().toISOString().substr(0, 10).split('-').reverse().join('-');
this.resultado = await this.getDolar(hoy);
console.log(this.resultado.data)
}
是的,Wait也可以这样做。但是,async/await是ECMAScript 2017的一部分,在Internet Explorer和较旧的浏览器中不受支持,因此您必须谨慎使用ECMAScript 2017的浏览器可用性
// Want to use async/await? Add the `async` keyword to your outer function/method.
async function getUser() {
try {
const response = await axios.get('/user?ID=12345');
console.log(response);
} catch (error) {
console.error(error);
}
}
标有async
的函数将始终返回承诺