组件中的异步计算 - VueJS? [英] Async Computed in Components - VueJS?

查看:30
本文介绍了组件中的异步计算 - VueJS?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找组件中异步计算方法的解决方案:

目前,我的组件是:

{{消息}}

<脚本>导出默认{计算:{消息:{得到 () {return api.get(`/users/${this.value.username}/message/`, {'headers': { 'Authorization': 'JWT ...' }}).then(response => response.data)}}},}

结果:{}

如何在Promise模式下重写?因为我认为我们可以通过写入 Promise 模式进行异步计算.

解决方案

计算属性基本上是缓存其结果的函数,这样就不必在每次需要时都计算它们.他们根据他们使用的反应值自动更新.

你的计算不使用任何反应性项目,所以它是一个计算没有意义.它现在返回一个 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);
  }
}

这篇关于组件中的异步计算 - VueJS?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆