如何在 vue 模板中使用异步函数?

rad*_*orz 3 async-await vue.js vuejs2

这是我的例子:

\n
<template>\n  <div v-for="id of SomethingChanging">\n    {{ getSomethingAsync(id) }}\n  </div>\n</template>\n\n<script>\nexport default {\n  ...\n  methods:{\n   async getSomethingAsync(id){\n      try {\n        const result = await getSomethingAPI(id)\n        return result.payload\n      } catch (e) {\n        console.log(e)\n      }\n    }\n  }\n}\n</script>\n\n
Run Code Online (Sandbox Code Playgroud)\n

我们都知道, \xe2\x80\x8basync 函数将返回一个有希望的对象......

\n

我该如何修复它以便页面返回真实的数据?

\n

Bou*_*him 7

不要尝试调用模板内的方法来渲染某些内容,因为这可能会带来一些问题,例如无限渲染,而不是您可以定义一个数据属性,您可以将其填充到创建的挂钩中,例如:

<template>
  <div v-for="item in result">
    {{ item }}
  </div>
</template>

<script>
export default {
  ...
 data() {
    return {
      result: []
    }
  },
  methods: {
    async getSomethingAsync(id) {
      try {
        const result = await axios.get('https://jsonplaceholder.typicode.com/todos/' + id)

        return result.data
      } catch (e) {
        console.log(e)
      }
    }
  },
  async created() {
    this.result = await Promise.all([...Array(5)].map((_, i) => {
      return this.getSomethingAsync(i + 1)
    }))
  }
</script>
Run Code Online (Sandbox Code Playgroud)

例子

// ignore the following two lines, they just disable warnings in "Run code snippet"
Vue.config.devtools = false;
Vue.config.productionTip = false;

new Vue({
  el: '#app',
  data() {
    return {
      result: []
    }
  },
  methods: {
    async getSomethingAsync(id) {
      try {
        const result = await axios.get('https://jsonplaceholder.typicode.com/todos/' + id)

        return result.data
      } catch (e) {
        console.log(e)
      }
    }
  },
  async created() {
    this.result = await Promise.all([...Array(5)].map((_, i) => {
      return this.getSomethingAsync(i + 1)
    }))
  }
})
Run Code Online (Sandbox Code Playgroud)
<html lang="en" dir="ltr">

<head>
  <meta charset="utf-8">
  <title></title>
  <link type="text/css" rel="stylesheet" href="//unpkg.com/bootstrap/dist/css/bootstrap.min.css" />

  <script src="https://unpkg.com/vue@2.5.17/dist/vue.js"></script>
  <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
  <script src="https://unpkg.com/vue-axios@2.1.4/dist/vue-axios.min.js"></script>
</head>

<body>
  <div id="app">
    <ul>
      <li v-for="item in result">
        {{ item.title }}
      </li>
    </ul>
  </div>
</body>

</html>
Run Code Online (Sandbox Code Playgroud)