更新时间:2023-09-19 23:29:04
计算属性基本上是缓存其结果的函数,这样就不必在每次需要时都计算它们.他们根据他们使用的反应值自动更新.
你的计算不使用任何反应性项目,所以它是一个计算没有意义.它现在返回一个 Promise(假设 then
的通常行为).
您想要实现的目标并不完全清楚,但我***的猜测是您应该创建一个数据项来保存 response.data
,并使您的 api.get
调用 created
钩子.类似的东西
出口默认{数据() {返回 {//...消息:[]};},创建(){api.get(`/users/${this.value.username}/message/`, {'标题':{'授权':'JWT ...'}}).then(response => this.messages = response.data);}}
I'm finding a solution to async computed method in Components:
Currently, my component is:
<div class="msg_content">
{{messages}}
</div>
<script>
export default {
computed: {
messages: {
get () {
return api.get(`/users/${this.value.username}/message/`, {'headers': { 'Authorization': 'JWT ...' }})
.then(response => response.data)
}
}
},
}
</script>
Result:
{}
How to rewrite it in Promise
mode? Because I think we can async computed by writing into Promise mode.
Computed properties are basically functions that cache their results so that they don't have to be calculated every time they are needed. They updated automatically based on the reactive values they use.
Your computed does not use any reactive items, so there's no point in its being a computed. It returns a Promise now (assuming the usual behavior of then
).
It's not entirely clear what you want to achieve, but my best guess is that you should create a data item to hold response.data
, and make your api.get
call in the created
hook. Something like
export default {
data() {
return {
//...
messages: []
};
},
created() {
api.get(`/users/${this.value.username}/message/`, {
'headers': {
'Authorization': 'JWT ...'
}
})
.then(response => this.messages = response.data);
}
}