Vue.js前端框架教程3:Vue setup语法糖和异步操作

文章目录

        • [script setup](#script setup)
        • Vue异步操作
          • [1. 使用 `async` 和 `await`](#1. 使用 asyncawait)
          • [2. 使用 Promise](#2. 使用 Promise)
          • [3. 在 `created` 或 `mounted` 钩子中执行异步操作](#3. 在 createdmounted 钩子中执行异步操作)
          • [4. 使用 `watch` 或 `watchEffect` 监听数据变化](#4. 使用 watchwatchEffect 监听数据变化)
          • [5. 使用 Composition API 的 `useAsync`](#5. 使用 Composition API 的 useAsync)
script setup

<script setup>Vue 3 中引入的一种新的组件语法糖,它提供了一种更简洁和更少样板代码的方式来编写组件。使用 <script setup>,你可以直接在 <script> 标签中使用 setup 函数中的代码,而不需要显式地定义 setup 函数。这种方式使得组件的逻辑更加集中和清晰。

以下是 <script setup> 的基本用法:

基本语法
html 复制代码
<script setup>
import { ref } from 'vue';

const count = ref(0);

function increment() {
  count.value++;
}
</script>

<template>
  <button @click="increment">{{ count }}</button>
</template>

在这个例子中,count 是一个响应式引用,increment 是一个方法,它们都可以直接在模板中使用,无需在 setup 函数中返回。

使用 Composition API

<script setup>Vue 3Composition API 配合得非常好,你可以轻松地使用 refreactivecomputed 等响应式 API

html 复制代码
<script setup>
import { ref, computed } from 'vue';

const firstName = ref('John');
const lastName = ref('Doe');

const fullName = computed(() => `${firstName.value} ${lastName.value}`);
</script>

<template>
  <p>{{ fullName }}</p>
</template>
组件定义

<script setup> 中,你也可以定义组件,并且它们会自动注册到当前组件中。

html 复制代码
<script setup>
import MyComponent from './MyComponent.vue';
</script>

<template>
  <my-component />
</template>
使用生命周期钩子

<script setup> 也支持生命周期钩子,如 onMountedonUpdated 等。

html 复制代码
<script setup>
import { onMounted } from 'vue';

onMounted(() => {
  console.log('组件已挂载');
});
</script>
模板引用

<script setup> 中,模板引用(如 ref 定义的响应式变量)可以直接在模板中使用。

html 复制代码
<script setup>
import { ref } from 'vue';

const inputRef = ref(null);
</script>

<template>
  <input :value="inputRef" @input="inputRef = $event.target.value" />
</template>
使用 definePropsdefineEmits

对于 propsemits<script setup> 提供了 definePropsdefineEmits 宏,使得定义更加简洁。

vue 复制代码
<script setup>
const props = defineProps(['title']);
const emit = defineEmits(['update']);
</script>

<template>
  <button @click="emit('update', props.title)">更新标题</button>
</template>
组合多个 <script setup> 标签

如果你的组件非常大,你可以将逻辑分割到多个 <script setup> 标签中。

html 复制代码
<script setup>
// Part 1: Feature A
import { ref } from 'vue';
const featureA = ref(0);
</script>

<script setup>
// Part 2: Feature B
import { computed } from 'vue';
const featureB = computed(() => `Feature B: ${featureA.value}`);
</script>

<template>
  <div>{{ featureB }}</div>
</template>

<script setup>Vue 3 中一个非常强大的特性,它使得组件的编写更加简洁和模块化,同时也提高了开发效率。

Vue异步操作

Vue 前端框架中,异步操作通常是必不可少的,尤其是在处理网络请求、定时任务、延迟操作等场景。Vue 提供了几种处理异步操作的方法,以下是一些常见的异步处理方式:

1. 使用 asyncawait

Vue 支持在组件的方法中使用 asyncawait 语法,这使得异步代码的编写更加直观和易于理解。

javascript 复制代码
<template>
  <button @click="handleClick">点击我</button>
</template>

<script>
export default {
  methods: {
    async handleClick() {
      try {
        const response = await fetch('/api/data');
        const data = await response.json();
        console.log(data);
      } catch (error) {
        console.error('请求失败:', error);
      }
    }
  }
}
</script>
2. 使用 Promise

Vue 中,你可以使用 Promise 来处理异步操作,并通过 .then().catch() 方法来处理成功和失败的情况。

javascript 复制代码
<template>
  <button @click="handleClick">点击我</button>
</template>

<script>
export default {
  methods: {
    handleClick() {
      fetch('/api/data')
        .then(response => response.json())
        .then(data => {
          console.log(data);
        })
        .catch(error => {
          console.error('请求失败:', error);
        });
    }
  }
}
</script>
3. 在 createdmounted 钩子中执行异步操作

Vue 组件的生命周期钩子中,你可以执行异步操作,例如在组件创建后或挂载后立即获取数据。

javascript 复制代码
<template>
  <div>{{ message }}</div>
</template>

<script>
export default {
  data() {
    return {
      message: ''
    };
  },
  created() {
    fetch('/api/data')
      .then(response => response.json())
      .then(data => {
        this.message = data.message;
      })
      .catch(error => {
        console.error('请求失败:', error);
      });
  }
}
</script>
4. 使用 watchwatchEffect 监听数据变化

Vue 3 中,watchwatchEffect 是响应式 API,可以用来监听数据的变化,并在变化时执行异步操作。

javascript 复制代码
<script setup>
import { ref, watch } from 'vue';

const data = ref(null);

watch(data, async (newValue, oldValue) => {
  if (newValue !== oldValue) {
    const response = await fetch(`/api/data/${newValue}`);
    const result = await response.json();
    console.log(result);
  }
});
</script>
5. 使用 Composition API 的 useAsync

Vue 3 中,你可以使用 Composition API 提供的 useAsync 组合函数来处理异步操作,这使得代码更加模块化和可重用。

javascript 复制代码
<script setup>
import { ref, computed } from 'vue';
import { useAsync } from '@vueuse/core';

const fetchData = (id) => fetch(`/api/data/${id}`).then(res => res.json());

const { result, error, loading } = useAsync(() => fetchData(1), { immediate: true });

console.log(result, error, loading);
</script>

这些方法可以帮助你在 Vue 前端应用中有效地处理异步操作,提高应用的响应性和用户体验。

相关推荐
tedcloud1233 小时前
UI-TARS-desktop部署教程:构建AI桌面自动化系统
服务器·前端·人工智能·ui·自动化·github
UXbot6 小时前
AI原型设计工具如何支持团队协作与快速迭代
前端·交互·个人开发·ai编程·原型模式
AC赳赳老秦6 小时前
供应链专员提效:OpenClaw自动跟踪物流信息、更新库存数据,异常自动提醒
java·大数据·服务器·数据库·人工智能·自动化·openclaw
夏日听雨眠6 小时前
LInux(逻辑地址与物理地址的区别,文件描述符,lseek函数)
linux·运维·网络
ZC跨境爬虫7 小时前
跟着MDN学HTML_day_48:(Node接口)
前端·javascript·ui·html·音视频
哲霖软件7 小时前
ERP 赋能非标自动化行业:破解物料与库存管理难题
运维·自动化
qq_542515418 小时前
Ubuntu 22.04.4 LTS安装ToDesk最新版打不开,无响应?旧版本4.7.2_277版本分享
linux·ubuntu·todesk
火车叼位8 小时前
替代 Tiny Win10 的 Linux 方案:Debian XFCE 精简桌面搭建
linux·运维
PieroPc8 小时前
CAMWATCH — 局域网摄像头监控系统 Fastapi + html
前端·python·html·fastapi·监控
小麦嵌入式8 小时前
FPGA入门(四):时序逻辑计数器原理与 LED 闪烁实现
linux·驱动开发·stm32·嵌入式硬件·fpga开发·硬件工程·dsp开发