百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 技术分类 > 正文

Vue3 新趋势:10 个最强 X 操作!(vue.3)

ztj100 2025-06-24 18:18 39 浏览 0 评论

Vue3 为前端开发带来了诸多革新,它不仅提升了性能,还提供了更简洁更强大API

以下是十个最值得学习和使用的 Vue3 API,它们将助力你的开发工作迈向新高度。

浅层响应式 API:shallowRef

Vue3 中,shallowRef 是一个用于创建浅层响应式引用的工具。与普通的 ref 不同,shallowRef 只会追踪其引用值变化,而不会深入到对象的内部属性。

这在处理复杂对象时非常实用,尤其当你不需要对象内部属性具有响应性时,可以显著提升性能。

import { shallowRef } from 'vue';

const data = shallowRef({ name: 'Vue', version: 3 });

数据保护利器:readonly 和shallowReadonly

readonlyshallowReadonly 用于保护数据不被意外修改。readonly 会将一个响应式对象转换为完全只读的对象,任何修改操作都会报错。

shallowReadonly 则只将对象的顶层属性设置为只读,嵌套对象的属性仍可以被修改。

import { readonly, shallowReadonly, reactive } from 'vue';

const userData = reactive({ name: 'User', details: { job: 'Developer' } });
const lockedUserData = readonly(userData); // 完全只读
const shallowLockedData = shallowReadonly(userData); // 浅层只读

自动追踪依赖:watchEffect(含停止、暂停、恢复操作)

watchEffect 是一个强大的响应式 API,它可以自动追踪响应式数据的依赖,并在依赖变化时重新执行副作用函数。

watch 不同,它不需要显式指定依赖项,非常适合用于数据同步和副作用管理。

停止、暂停和恢复侦听器

import { ref, watchEffect } from'vue';

const count = ref(0);
const { stop, pause, resume } = watchEffect(() => {
console.log('count changed:', count.value);
});

// 暂停侦听器
pause();

// 稍后恢复
resume();

// 停止侦听器
stop();

性能优化神器:v-memo

v-memo 是 Vue3 中用于优化列表渲染性能的指令。它允许你在模板中缓存列表项的渲染,只有当指定的依赖项发生变化时,才会重新渲染列表项。

这对于频繁更新的长列表来说,性能提升非常显著。

<template>
  <ul>
    <li v-for="item in list" :key="item.id" v-memo="[item.id, item.title]">
      {{ item.title }} - {{ item.content }}
    </li>
  </ul>
</template>

简化组件双向绑定:defineModel()

defineModel() 是 Vue3.4 中引入的一个新 API,旨在简化父子组件之间的双向绑定。

它允许组件直接操作父组件传递的 v-model 数据,而无需显式地定义 propsemits

基本使用

<!-- 父组件 -->
<template>
  <div>
    <CustomComponent v-model="userName" />
  </div>
</template>

<script setup>
import { ref } from 'vue';
import CustomComponent from './CustomComponent.vue';

const userName = ref('前端开发爱好者');
</script>
<!-- 子组件 -->
<template>
  <input type="text" v-model="modelValue" />
</template>

<script setup>
const modelValue = defineModel();
</script>

带参数/定义多个 v-model

<!-- 父组件 -->
<template>
  <div>
    <CustomComponent
      v-model="userName"
      v-model:title="title"
      v-model:subTitle="subTitle"
    />
  </div>
</template>

<script setup>
import { ref } from 'vue';
import CustomComponent from './CustomComponent.vue';

const userName = ref('前端开发爱好者');
const title = ref('前端开发爱好者_title');
const subTitle = ref('前端开发爱好者_subTitle');
</script>
<!-- 子组件 -->
<template>
  <input type="text" v-model="modelValue" />
  <input type="text" v-model="title" />
  <input type="text" v-model="subTitle" />
</template>

<script setup>
const modelValue = defineModel();
const title = defineModel('title');
const subTitle = defineModel('subTitle');
</script>

顶层 await:简化异步操作

Vue3 支持顶层 await,这意味着你可以在模块顶层使用 await,而无需将其包裹在异步函数中。

这对于需要在模块加载时执行异步操作的场景非常有用。

<script setup>
const fetchData = async () => {
  const response = await fetch('https://api.example.com/data');
  return response.json();
};

const data = await fetchData();
</script>

动态组件:< component >

动态组件是 Vue3 中用于动态渲染组件的标签,它允许你在同一个位置上加载不同的组件,从而提高用户体验。

基本用法

动态组件的核心是 <component> 标签和 is 特性。通过绑定 is 的值,可以动态渲染不同的组件。

<template>
  <div>
    <button @click="toggleComponent">Toggle Component</button>
    <component :is="currentComponent"></component>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import ComponentA from './ComponentA.vue';
import ComponentB from './ComponentB.vue';

const currentComponent = ref('ComponentA');

const toggleComponent = () => {
  currentComponent.value = currentComponent.value === 'ComponentA' ? 'ComponentB' : 'ComponentA';
};
</script>

高级用法:异步组件

异步组件是一种可以延迟加载组件的技术,可以提高性能。

<template>
  <div>
    <button @click="loadComponentA">Load Component A</button>
    <button @click="loadComponentB">Load Component B</button>
    <component :is="currentComponent"></component>
  </div>
</template>

<script setup>
import { ref } from'vue';

const currentComponent = ref(null);

const loadComponentA = async () => {
const component = awaitimport('./ComponentA.vue');
  currentComponent.value = component.default;
};

const loadComponentB = async () => {
const component = awaitimport('./ComponentB.vue');
  currentComponent.value = component.default;
};
</script>

空间传送门:< Teleport >

<Teleport> 是 Vue3 中用于将组件的内容渲染到指定的 DOM 节点中的 API。

它可以帮助你解决弹窗下拉菜单等组件的层级和样式问题。

<template>
  <button @click="showModal = true">Open Modal</button>
  <Teleport to="body">
    <div v-if="showModal" class="modal">
      <h2>Modal</h2>
      <button @click="showModal = false">Close</button>
    </div>
  </Teleport>
</template>

<script setup>
import { ref } from 'vue';
const showModal = ref(false);
</script>

隐形容器:Fragment

Vue3 中的 Fragment 允许你在模板中没有根节点,减少多余的 DOM 节点,提升渲染性能。这对于列表组件来说非常有用。

<template>
  <template v-for="item in list" :key="item.id">
    <h2>{{ item.title }}</h2>
    <p>{{ item.content }}</p>
  </template>
</template>

<script setup>
import { ref } from 'vue';
const list = ref([{ id: 1, title: 'Title 1', content: 'Content 1' }]);
</script>

自定义指令:封装可重用逻辑(v-debounce 实现)

自定义指令是 Vue3 中用于封装可重用逻辑的工具,例如防抖功能。

以下是如何创建一个防抖指令 v-debounce

import { createApp } from'vue';

const app = createApp({});

// 注册自定义指令v-debounce
app.directive('debounce', {
  mounted(el, binding) {
    let timer;
    // 给 el 绑定事件,默认 click 事件
    el.addEventListener(binding.arg || 'click', () => {
      if (timer) {
        clearTimeout(timer);
      }
      // 回调函数延迟执行
      timer = setTimeout(() => {
        binding.value();
      }, binding.modifiers.time || 300);
    });
  }
});

app.mount('#app');

使用示例:

<template>
  <!-- 300毫秒内多次点击只会执行一次 -->
  <button v-debounce:click.time="500" @click="fetchData">请求数据</button>
</template>

<script setup>
import { ref } from 'vue';

const fetchData = () => {
      console.log('执行数据请求');
    };
</script>

Vue3 的这些强大 API 为开发者提供了更高效、更灵活的开发体验。

掌握这些工具,不仅能显著提升开发效率,还能让你的代码更加简洁和可维护。

在实际项目中,合理运用这些 API,将使你的应用性能更优、结构更清晰。无论是初学者还是有经验的开发者,都应深入学习这些特性,以充分利用 Vue3 的优势。

相关推荐

Linux集群自动化监控系统Zabbix集群搭建到实战

自动化监控系统...

systemd是什么如何使用_systemd/system

systemd是什么如何使用简介Systemd是一个在现代Linux发行版中广泛使用的系统和服务管理器。它负责启动系统并管理系统中运行的服务和进程。使用管理服务systemd可以用来启动、停止、...

Linux服务器日常巡检脚本分享_linux服务器监控脚本

Linux系统日常巡检脚本,巡检内容包含了,磁盘,...

7,MySQL管理员用户管理_mysql 管理员用户

一、首次设置密码1.初始化时设置(推荐)mysqld--initialize--user=mysql--datadir=/data/3306/data--basedir=/usr/local...

Python数据库编程教程:第 1 章 数据库基础与 Python 连接入门

1.1数据库的核心概念在开始Python数据库编程之前,我们需要先理解几个核心概念。数据库(Database)是按照数据结构来组织、存储和管理数据的仓库,它就像一个电子化的文件柜,能让我们高效...

Linux自定义开机自启动服务脚本_linux添加开机自启动脚本

设置WGCloud开机自动启动服务init.d目录下新建脚本在/etc/rc.d/init.d新建启动脚本wgcloudstart.sh,内容如下...

linux系统启动流程和服务管理,带你进去系统的世界

Linux启动流程Rhel6启动过程:开机自检bios-->MBR引导-->GRUB菜单-->加载内核-->init进程初始化Rhel7启动过程:开机自检BIOS-->M...

CentOS7系统如何修改主机名_centos更改主机名称

请关注本头条号,每天坚持更新原创干货技术文章。如需学习视频,请在微信搜索公众号“智传网优”直接开始自助视频学习1.前言本文将讲解CentOS7系统如何修改主机名。...

前端工程师需要熟悉的Linux服务器(SSH 终端操作)指令

在Linux服务器管理中,SSH(SecureShell)是远程操作的核心工具。以下是SSH终端操作的常用命令和技巧,涵盖连接、文件操作、系统管理等场景:一、SSH连接服务器1.基本连接...

Linux开机自启服务完全指南:3步搞定系统服务管理器配置

为什么需要配置开机自启?想象一下:电商服务器重启后,MySQL和Nginx没自动启动,整个网站瘫痪!这就是为什么开机自启是Linux运维的必备技能。自启服务能确保核心程序在系统启动时自动运行,避免人工...

Kubernetes 高可用(HA)集群部署指南

Kubernetes高可用(HA)集群部署指南本指南涵盖从概念理解、架构选择,到kubeadm高可用部署、生产优化、监控备份和运维的全流程,适用于希望搭建稳定、生产级Kubernetes集群...

Linux项目开发,你必须了解Systemd服务!

1.Systemd简介...

Linux系统systemd服务管理工具使用技巧

简介:在Linux系统里,systemd就像是所有进程的“源头”,它可是系统中PID值为1的进程哟。systemd其实是一堆工具的组合,它的作用可不止是启动操作系统这么简单,像后台服务...

Red Hat Enterprise Linux 10 安装 Kubernetes (K8s) 集群及高级管理

一、前言...

Linux下NetworkManager和network的和平共处

简介我们在使用CentoOS系统时偶尔会遇到配置都正确但network启动不了的问题,这问题经常是由NetworkManager引起的,关闭NetworkManage并取消开机启动network就能正...

取消回复欢迎 发表评论: