繁体   English   中英

Vue.js 异步组件未更新模板

[英]Vue.js async component not updating template

我有一个 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>

您可以使用v-if来隐藏/显示元素,而不是切换 class。 我不确定您的hide class 是什么样的,但我猜它类似于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">

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM