在Vue3的
<script setup>中,async关键字的使用取决于场景:
- 使用await时必须加async;
- 使用.then()或同步操作时可省略;
- Vue3.3+支持顶层await无需async。
async的作用是让函数返回Promise并允许使用await。
若代码含await却省略async会导致语法错误。
文中提供了具体代码示例说明何时必须或可以省略async关键字。
在 <script setup lang="ts"> 中,async 通常不能省略,但有特殊情况。
1. 需要 async 的情况(最常见)
当你需要在 onMounted、watch、computed 等钩子或响应式API中使用 await 时:
TypeScript
// ✅ 必须要有 async
onMounted(async () => {
const data = await fetchData() // 使用 await
result.value = data
})
// ✅ 必须要有 async
const fetchData = async () => {
const response = await axios.get('/api/data')
return response.data
}
2. 可以省略 async 的情况
方式一:使用 .then() 替代 await
TypeScript
// ✅ 可以省略 async
onMounted(() => {
fetchData().then(data => {
result.value = data
})
})
方式二:不使用异步操作
TypeScript
// ✅ 可以省略 async
onMounted(() => {
result.value = '立即设置的值'
})
3. 针对你的原始代码
TypeScript
// 原始代码(必须要有 async)
onMounted(async () => {
result.value = await new Promise<string>((resolve) => {
setTimeout(() => {
resolve('hello world')
}, 10000)
})
})
// 等价改写(可以省略 async)
onMounted(() => {
new Promise<string>((resolve) => {
setTimeout(() => {
resolve('hello world')
}, 10000)
}).then(value => {
result.value = value // 使用 .then() 替代 await
})
})
4. async 的作用
async 关键字的作用是:
-
让函数返回一个 Promise
-
允许在函数内部使用
await -
自动包装返回值为 Promise
TypeScript
// 这两个函数是等价的
async function foo() { return 1 }
function foo() { return Promise.resolve(1) }
5. ue 3.3+ 的特殊情况
Vue 3.3+ 引入了 <script setup> 的顶层 await 支持:
TypeScript
<script setup lang="ts">
// ✅ Vue 3.3+ 支持,不需要 async
const data = await fetchData() // 顶层 await
// 但生命周期钩子内仍需 async
onMounted(async () => {
// ...
})
</script>
总结:
| 场景 | 是否需要 async |
|---|---|
使用 await |
必须 |
使用 .then() |
不需要 |
| 同步操作 | 不需要 |
Vue 3.3+ 顶层 await |
不需要(在顶层) |
在你的代码中,由于使用了 await,所以 async 不能省略。 如果省略了 async,但保留了 await,会导致语法错误。