Vue3组合式Api script setup模式中顶层使用await报Top-level ‘await‘ expressions are only allowed when the ‘module‘

文章讲述了在Vue3中使用Suspense组件时遇到的顶级await表达式Eslint错误,以及如何通过禁用Vetur并启用Volar,或者修改tsconfig.json来解决问题。同时,文章提供了异步组件加载和Suspense组件的使用示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

今天练习Vue3的Suspense组件的时候碰到在Vue3组合式Api script setup模式中顶层使用await时报错Eslint错误(能正常编译),错误提示是:

Top-level 'await' expressions are only allowed when the 'module' option is set to 'es2022', 'esnext', 'system', 'node16', or 'nodenext', and the 'target' option is set to 'es2017' or higher.Vetur(1378)

如截图:

解决方案1:检查项目中是否是使用了Vetur

检查项目中是否是使用了Vetur,检查项目中是否是使用了Vetur,检查项目中是否是使用了Vetur。

重要的事情说3遍,Vue3不能搭配Vetur,会有很多奇葩的格式校验问题。

如果安装了,并且启用状态,将其Disable掉就好,可以仅禁用当前工程。因为多数时候我们会同时维护vue2项目和vue3项目。

 

Vue3搭配的是Volar。

解决方案2:修改项目中的tsconfig.json

一般情况下,使用方案1就都解决了,如果方案1还有问题,可以尝试一下方案2。

修改项目中的tsconfig.json

原配置文件:

{
  "files": [],
  "references": [
    {
      "path": "./tsconfig.node.json"
    },
    {
      "path": "./tsconfig.app.json"
    },
    {
      "path": "./tsconfig.vitest.json"
    }
  ]
}

修改为:


{
  "files": [],
  "references": [
    {
      "path": "./tsconfig.node.json"
    },
    {
      "path": "./tsconfig.app.json"
    },
    {
      "path": "./tsconfig.vitest.json"
    }
  ],
  // https://www.typescriptlang.org/tsconfig#compilerOptions
  "compilerOptions": {
    "esModuleInterop": true,
    "lib": ["es2020"],
    "module": "es2022",
    "preserveConstEnums": true,
    "moduleResolution": "node",
    "strict": true,
    "sourceMap": true,
    "target": "es2022",
    "types": ["node"],
    "outDir": "dist"
  },
  "include": ["src/**/*"],
  "exclude": ["node_modules"]
}

参考文档:

javascript - Top-level ‘await’ expressions are only allowed when the ‘module’ option is set to ‘esnext' - Stack Overflow

至此,问题搞定。

这里贴上Suspense相关的测试代码,文档参考官方文档:

Suspense | Vue.js

Async1.vue,单文件组件,将会被AsyncWrapper.vue以异步组件的方式加载:

<template>
  <div>
    <h2>Async1</h2>
  </div>

</template>
<script lang="ts" setup>
  console.log('[Async1.vue] setup :: enter')
</script>

Async2.vue,单文件组件,将会被AsyncWrapper.vue以异步组件的方式加载:

<template>
  <div>
    <h2>Async2</h2>
  </div>

</template>
<script lang="ts" setup>
  console.log('[Async2.vue] setup :: enter')
</script>

Async3.vue,单文件组件,script setup的顶层代码中使用await

<template>
  <div>
    <h2>Async3, use await</h2>
    <h2> {{ refData }} </h2>
  </div>

</template>
<script lang="ts" setup>
  import { ref } from 'vue'
  console.log('[Async3.vue] setup :: enter')
  const p = new Promise((resolve,reject)=> {
    setTimeout(() => {
      resolve('Async 3 ok~~~')
    }, 5000)
  })
  const data =await p
  console.log('[Async3.vue] setup :: async end')
  const refData = ref(data)
</script>

AsyncWrapper,以异步方式加载Async1.vue、Async2.vue,导入底层具备await的组件。AsyncWrapper成为一个异步组件容器,有3个异步依赖项。

<template>
  <div>
    <h2>AsyncWrapper</h2>
    <Async1></Async1>
    <Async2></Async2>
    <Async3></Async3>
  </div>

</template>
<script lang="ts" setup>
import {ref, defineAsyncComponent} from 'vue'
// script setup 单文件组件,顶层使用了await
import Async3 from './Async3.vue'
console.log('[AsyncWrapper.vue] setup :: enter')

// 异步组件,异步的加载单文件组件
const Async1 = defineAsyncComponent(()=> {
  return new Promise((resolve, reject)=> {
    setTimeout(()=> {
      import('./Async1.vue').then((res)=> {
        resolve(res)
      })
    }, 2000)
  })
})
// 异步组件,异步的加载单文件组件
const Async2 = defineAsyncComponent(()=> {
  return new Promise((resolve, reject)=> {
    setTimeout(()=> {
      import('./Async2.vue').then((res)=> {
        resolve(res)
      })
    }, 4000)
  })
})

</script>

AsyncTester.vue,使用Suspense统一管理几个异步加载的组件内容项

<template>
  <h2>测试异步组件相关逻辑</h2>
  <Suspense>
    <AsyncWrapper />
    <template #fallback>
      加载中。。。
    </template>
  </Suspense>
</template>

<script lang="ts" setup>
import AsyncWrapper from '../components/AsyncWrapper.vue'
</script>

// 结果满足预期

1,Suspense启动的时候,在内存中渲染默认插槽内容组件,AsyncWrapper,发现里面有异步加载组件Async1.vue、Async2.vue以及顶层有await的Async3.vue,因此进入挂起状态,显示#fallback插槽,界面上看到加载中。

2,等3个异步等完成之后,三个组件内容,同时渲染到界面上。

3,这在管理多个异步加载组件内容的时候,感觉还是很有用的。

风险: 这还是一个实验性的内置组件,它不一定会最终成为稳定功能,并且在稳定之前相关 API 也可能会发生变化。

Vue 3 中,setup 函数可以使用 async/await 进行异步操作。在表单验证中,你可以使用 async/await 来等待异步验证结果。 下面是一个简单的例子: ``` <template> <form @submit.prevent="submitForm"> <div> <label for="username">Username:</label> <input type="text" v-model="username"> <div v-if="usernameError">{{ usernameError }}</div> </div> <div> <label for="password">Password:</label> <input type="password" v-model="password"> <div v-if="passwordError">{{ passwordError }}</div> </div> <button type="submit">Submit</button> </form> </template> <script> import { ref } from &#39;vue&#39;; export default { setup() { const username = ref(&#39;&#39;); const password = ref(&#39;&#39;); const usernameError = ref(&#39;&#39;); const passwordError = ref(&#39;&#39;); const validateUsername = async () => { if (!username.value) { usernameError.value = &#39;Username is required&#39;; } else { usernameError.value = &#39;&#39;; } }; const validatePassword = async () => { if (!password.value) { passwordError.value = &#39;Password is required&#39;; } else { passwordError.value = &#39;&#39;; } }; const submitForm = async () => { await validateUsername(); await validatePassword(); if (!usernameError.value && !passwordError.value) { // Submit the form } }; return { username, password, usernameError, passwordError, submitForm, }; }, }; </script> ``` 在这个例子中,我们使用了 ref 来创建响应式的变量,然后定义了两个异步的验证函数 validateUsername 和 validatePassword,这些函数会根据输入的值设置相应的错误信息。 在 submitForm 函数中,我们使用await 来等待异步验证结果。如果两个验证都通过了,就可以提交表单了。 注意,需要使用 await 来等待异步验证结果,否则 submitForm 函数会在异步验证结果还未返回时就执行完毕,无法正确处理验证结果。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值