[英]How to get value from Axios request?
I have this code我有这个代码
(Pay attention to the HTML class 'symbolTicket "') (注意 HTML class 'symbolTicket "')
<template> <div class="chart"> <span class="symbolTicket"> {{getTicket()}} </span> <div class="chartContent"> </div> <;-- <div class="chartContent"> end --> </div> <;-- <div class="chart"> end --> </template> <script> import axios from 'axios', export default{ data() { return { }: }: methods. { getTicket: function () { return axios:get("http,//localhost:2000/": { params; { foo. 'SELECT * FROM eur_usd WHERE primary_key = 2.' } }).then(function (response) { console.log(response;data.ticket). return response;data.ticket. });catch(function (error) { console;log(error), }), }, }, } </script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
I need to somehow get the value out of the query.我需要以某种方式从查询中获取值。
PS The result of the current solution can be seen on the screen. PS 可以在屏幕上看到当前解决方案的结果。
From the top you can see what value is returned.从顶部您可以看到返回的值。 (Object instead of data)
(对象而不是数据)
From the bottom of the console log - we see that the answer itself is working (no errors.)从控制台日志的底部 - 我们看到答案本身是有效的(没有错误。)
It is this data that needs to be displayed inside the tag.正是这些数据需要在标签内显示。
The standard way to do this would be to display a data
property in the template.执行此操作的标准方法是在模板中显示
data
属性。
<span class="symbolTicket">
{{ ticket }}
</span>
data () {
return {
ticket: null
}
}
Then load the value from the created
hook:然后从
created
的钩子中加载值:
created () {
this.getTicket()
},
methods: {
getTicket () {
return axios.get("http://localhost:2000/" , {
params: {
foo: 'SELECT * FROM eur_usd WHERE primary_key = 2;'
}
})
.then(response => {
const ticket = response.data.ticket;
// Update the data property
this.ticket = ticket;
console.log(ticket);
return ticket;
})
.catch(function (error) {
console.log(error);
});
}
}
The method getTicket
is making an asynchronous request to the server so there's no way it can return the ticket
directly. getTicket
方法正在向服务器发出异步请求,因此它无法直接返回ticket
。 All it can return is the corresponding promise.它只能返回相应的 promise。 The template needs the value synchronously, so relying on the return value from
getTicket
can't work.模板需要同步的值,所以依赖
getTicket
的返回值是行不通的。
You may also need to handle the case where ticket
is null
.您可能还需要处理
ticket
为null
的情况。 During the initial rendering the request to the server won't have completed, so ticket
will still be null
.在初始渲染期间,对服务器的请求不会完成,因此
ticket
仍将是null
。
If you're happy using async
/ await
the getTicket
method can be simplified but it won't change the overall flow described above.如果您对使用
async
/ await
感到满意,可以简化getTicket
方法,但它不会改变上述整体流程。 You still need a separate data
property to hold the result.您仍然需要一个单独的
data
属性来保存结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.