Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

vue async

作者:炼狱死神   发布日期:2025-12-29   浏览:88

// 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>):

    • 使用了 Vue 3 的组合式 API (setup 函数)。
    • ref 用于创建响应式的 message 变量。
    • fetchData 是一个异步函数,使用 async/await 来处理异步操作(例如 API 请求)。
    • try...catch 块用于捕获可能的错误,并在发生错误时更新 message 的值。
  • 样式部分 (<style scoped>):

    • 可以根据需要添加样式,这里留空。

这个示例展示了如何在 Vue 3 中使用 async/await 来处理异步操作。

上一篇:vue2 ref

下一篇:vite+vue+ts

大家都在看

vue.js devtools用法

vue js for循环

highlight.js vue

vue.config.js 配置

vue.config.js 配置代理

vue.config.js configu

node.js vue

vue3 写法

vue3组件传值的方式

vue3 子路由

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站