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

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

问题描述

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

I'm finding a solution to async computed method in Components:

当前,我的组件是:

<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>

结果: {}

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

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.

您的计算所得不使用任何反应性项目,因此将其用作计算毫无意义.它将立即返回一个Promise(假定 then 的常规行为).

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).

尚不清楚您要实现什么,但是我最好的猜测是您应该创建一个数据项来保存 response.data ,并创建您的 api.get 调用 created 钩子.像

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天全站免登陆