【问题标题】:Vue.js async component not updating templateVue.js 异步组件不更新模板
【发布时间】:2020-05-04 07:49:51
【问题描述】:

我有一个 Vue 组件,我在其中执行了一堆异步调用,然后应该填充我的模板。但是,似乎没有任何更新,即使我可以在控制台中看到我的数据正在返回。我对 Vue 很陌生,所以我一定遗漏了一些东西。这是我的代码的简化版本:

<template>
  <div id="my_component">
        <div v-bind:class="{ hidden: !isLoading }">
      <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" style="margin:auto;background:#fff;display:block;" width="200px" height="200px" viewBox="0 0 100 100" preserveAspectRatio="xMidYMid">
        <circle cx="50" cy="50" fill="none" stroke="#1ba4de" stroke-width="4" r="15" stroke-dasharray="70.68583470577033 25.561944901923447">
          <animateTransform attributeName="transform" type="rotate" repeatCount="indefinite" dur="0.9803921568627451s" values="0 50 50;360 50 50" keyTimes="0;1"></animateTransform>
        </circle>
      </svg>
    </div>

    <div v-bind:class="{ hidden: isLoading }">
      <h1>{{ result.title }}</h1>
    </div>
  </div>
</template>


<script>
export default {
  name: 'MyComponent',
  data () {
    return {
      isLoading: true,
      result: null
    }
  },
  async created () {
    this.result = await myLongRunningAsyncFunction();
    this.isLoading = true;
    console.log(this.result) // Logs result of myLongRunningAsyncFunction()
  }
  methods: {
    myLongRunningAsyncFunction: async function() {
     // Make a bunch of API calls and get some data
    }
  }
}
</script>

【问题讨论】:

  • 不应该是created钩子中的this.isLoading = false;吗?

标签: javascript vue.js async-await


【解决方案1】:

您可以使用v-if 来隐藏/显示元素,而不是切换类。我不确定你的 hide 类是什么样的,但我猜它类似于 display: none 女巫的效率较低。

<div v-if="!isLoading">
    <h1>{{ result.title }}</h1>
</div>

您还需要将isLoading 设置为false

async created () {
    this.result = await myLongRunningAsyncFunction();
    this.isLoading = false;
    console.log(this.result) // Logs result of myLongRunningAsyncFunction()
}

同样在你的第一个 div 中,这看起来会更好:

 <div v-bind:class="{ hidden: !isLoading }">

到这里:

 <div v-if="isLoading">

【讨论】:

  • 酷,谢谢。作为我自己的练习,我试图回到第一原则,并发现我的代码实际上存在一个问题,导致它无法正常工作!这些都是很好的建议。我会将其设置为接受的答案:)
猜你喜欢
  • 1970-01-01
  • 2017-06-05
  • 2018-04-12
  • 1970-01-01
  • 2015-09-20
  • 2020-11-07
  • 2020-02-04
  • 2017-06-28
  • 2011-08-24
相关资源
最近更新 更多