// Vue 3 中使用 async/await 的示例
<template>
<div>
<h1>{{ message }}</h1>
<button @click="fetchData">获取数据</button>
</div>
</template>
<script>
import { ref } from 'vue';
export default {
setup() {
const message = ref('点击按钮以获取数据');
// 定义一个异步函数来获取数据
const fetchData = async () => {
try {
// 模拟 API 请求
const response = await fetch('https://jsonplaceholder.typicode.com/posts/1');
const data = await response.json();
// 更新组件的状态
message.value = `从 API 获取的数据: ${data.title}`;
} catch (error) {
message.value = '请求失败,请稍后再试';
console.error(error);
}
};
return {
message,
fetchData
};
}
};
</script>
<style scoped>
/* 样式可以根据需要添加 */
</style>
模板部分 (<template>):
<h1>) 和一个按钮 (<button>)。fetchData 方法。脚本部分 (<script>):
setup 函数)。ref 用于创建响应式的 message 变量。fetchData 是一个异步函数,使用 async/await 来处理异步操作(例如 API 请求)。try...catch 块用于捕获可能的错误,并在发生错误时更新 message 的值。样式部分 (<style scoped>):
这个示例展示了如何在 Vue 3 中使用 async/await 来处理异步操作。
上一篇:vue2 ref
下一篇:vite+vue+ts
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站