【问题标题】:Why did I get blank (empty) content when I used async setup() in Vue.js 3?当我在 Vue.js 3 中使用 async setup() 时,为什么会得到空白(空)内容?
【发布时间】:2021-01-08 13:21:23
【问题描述】:

问题

我在 Vue.js 3 中使用 async setup(),但我的 HTML 内容消失了。我的组件模板没有插入 HTML,但是当我删除 async 和 await 前缀时,我的 HTML 内容又回来了。我该如何解决这个问题?

async setup () {
    const data = ref(null)
    try {
        const res = await fetch('api')
        data.value = res.json()
    }
    catch (e) {
        console.error(e)
    }
    return {
        data
    }
}

我试过了

  1. 我检查了 fetch,它返回了正确的响应
  2. 我试过<Suspense>标签,但还是同样的问题

【问题讨论】:

    标签: vue.js vue-component vuejs3 vue-composition-api


    【解决方案1】:

    您的组件的async setup() 看起来很好,除了缺少await res.json(),这仍然不会导致您看到的问题。我怀疑您对<Suspense> 的使用不正确。

    要在组件中使用async setup(),父组件必须在<Suspense> 标签中使用该组件:

    <!-- Parent.vue -->
    <template>
     <Suspense>
       <MyAsyncComponent />
     </Suspense>
    </template>
    

    您还可以使用&lt;Suspense&gt;defaultfallback 插槽来显示加载指示器,同时等待子组件的设置解决:

    <!-- Parent.vue -->
    <template>
     <Suspense>
       <template #default>
         <MyAsyncComponent />
       </template>
       <template #fallback>
         <span>Loading...</span>
       </template>
     </Suspense>
    </template>
    

    demo

    【讨论】:

    • 我在这个确切的问题上浪费了几个小时,你的回答是救命稻草,所以谢谢你!!
    • 只想说这个答案是金。谢谢。
    【解决方案2】:

    文件 parent.vue

    <template>
      <!-- parent add <suspense> -->
      <suspense>
        <child />
      </suspense>
    </template>
    
    <script>
    import Child from './child.vue'
    
    export default {
      components: {
        child
      },
      setup() {
        return {}
      }
    }
    </script>
    
    

    文件 child.vue

    <template>
      <div>child</div>
    </template>
    
    <script>
    export default {
      async setup() {
        return {}
      }
    }
    </script>
    
    

    对于child.vue,使用async setup...。对于parent.vue,需要将&lt;suspense&gt;添加到child.vue

    【讨论】:

      猜你喜欢
      • 2018-09-03
      • 2020-09-05
      • 1970-01-01
      • 2021-11-27
      • 1970-01-01
      • 2011-08-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多