Javascript 组件中的异步计算 - VueJS?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/48641295/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 04:11:59  来源:igfitidea点击:

Async Computed in Components - VueJS?

javascriptvue.jsvuejs2vue-component

提问by KitKit

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 Promisemode? Because I think we can async computed by writing into Promise mode.

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

采纳答案by Roy J

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

您的计算不使用任何反应性项目,因此将其作为计算没有意义。它现在返回一个 Promise(假设 的通常行为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.getcall in the createdhook. Something like

您想要实现的目标并不完全清楚,但我最好的猜测是您应该创建一个数据项来 hold response.data,并api.getcreatedhook 中进行调用。就像是

export default {
  data() {
      return {
        //...
        messages: []
      };
  },
  created() {
    api.get(`/users/${this.value.username}/message/`, {
        'headers': {
          'Authorization': 'JWT ...'
        }
      })
      .then(response => this.messages = response.data);
  }
}

回答by Roy J

es7 makes doing this quite trivial by using asyncand awaitin conjunction with axios' returned promise. You'll need the vue-async-computedpackage.

es7 通过使用asyncawait结合 axios 返回的 promise使这件事变得非常简单。你需要vue-async-computed包。

export default {
   asyncComputed: {
       async myResolvedValue() {
          return await api.get(`/users/${this.value.username}/message/`, {'headers': { 'Authorization': 'JWT ...' }})
              .then(response => response.data)
       }
    }
}