Vue3 从入门到精通:全面掌握前端框架的进阶之路

news/2025/2/15 9:16:35/

在这里插入图片描述

一、Vue3 简介

Vue.js 是一款流行的 JavaScript 前端框架,用于构建用户界面。Vue3 作为 Vue.js 的重大升级版本,带来了诸多性能提升和新特性。它采用了 Proxy 实现数据响应式系统,优化了虚拟 DOM 算法,使得应用在运行时更加高效。同时,Composition API 的引入为组件逻辑复用和代码组织提供了更灵活的方式,让开发者能够更优雅地处理复杂业务逻辑。

二、环境搭建

2.1 安装 Node.js

Vue3 项目基于 Node.js 运行,首先需要从 Node.js 官网 下载并安装最新版本的 Node.js。安装完成后,在命令行中输入 node -vnpm -v 检查是否安装成功,这两个命令会分别输出版本号。

2.2 创建 Vue3 项目

使用 Vue CLI 是创建 Vue3 项目最便捷的方式。如果尚未安装 Vue CLI,可以通过以下命令进行全局安装:

npm install -g @vue/cli

安装完成后,使用以下命令创建一个新的 Vue3 项目:

vue create my - vue3 - project

在创建过程中,会提示选择预设配置,可根据项目需求选择默认配置或手动选择特性。例如,选择手动配置可以勾选路由、状态管理等功能。

三、Vue3 基础语法

3.1 模板语法

Vue3 的模板语法与 Vue2 基本相似,但在一些细节上有所改进。例如,插值表达式依然使用 {{ }},可以在其中插入变量、表达式:

<template><div><p>{{ message }}</p><p>{{ 1 + 2 }}</p></div>
</template><script setup>
import { ref } from 'vue';const message = ref('Hello, Vue3!');
</script>

指令方面,常见的 v - ifv - forv - bind(缩写为 :)、v - on(缩写为 @)等依然可用。例如,使用 v - if 进行条件渲染:

<template><div><p v - if="isShow">This is a conditional paragraph.</p></div>
</template><script setup>
import { ref } from 'vue';const isShow = ref(true);
</script>

使用 v - for 进行列表渲染:

<template><div><ul><li v - for="(item, index) in items" :key="index">{{ item }}</li></ul></div>
</template><script setup>
import { ref } from 'vue';const items = ref(['Apple', 'Banana', 'Cherry']);
</script>

3.2 响应式数据

在 Vue3 中,主要使用 refreactive 来创建响应式数据。
ref 用于创建一个包含响应式数据的引用,基本数据类型和复杂数据类型都适用。例如:

<template><div><p>{{ count }}</p><button @click="increment">Increment</button></div>
</template><script setup>
import { ref } from 'vue';const count = ref(0);
const increment = () => {count.value++;
};
</script>

注意,访问和修改 ref 定义的数据时,需要通过 .value 属性。

reactive 用于创建一个响应式的对象或数组。例如:

<template><div><p>{{ user.name }}</p><p>{{ user.age }}</p><button @click="updateUser">Update User</button></div>
</template><script setup>
import { reactive } from 'vue';const user = reactive({name: 'John',age: 30
});const updateUser = () => {user.age++;
};
</script>

3.3 组件基础

Vue3 组件是构建应用的基本单元。定义一个组件可以使用 defineComponent 函数(在 script setup 语法糖下可省略)。例如,创建一个简单的子组件 MyComponent.vue

<template><div><p>{{ msg }}</p></div>
</template><script setup>
import { ref } from 'vue';const msg = ref('This is a sub - component');
</script>

在父组件中使用该子组件:

<template><div><MyComponent /></div>
</template><script setup>
import MyComponent from './MyComponent.vue';
</script>

组件之间可以通过 props 传递数据,例如在父组件中传递数据给子组件:

<template><div><MyComponent :message="parentMessage" /></div>
</template><script setup>
import { ref } from 'vue';
import MyComponent from './MyComponent.vue';const parentMessage = ref('Hello from parent');
</script>

子组件 MyComponent.vue 接收 props:

<template><div><p>{{ message }}</p></div>
</template><script setup>
import { defineProps } from 'vue';const props = defineProps({message: String
});
</script>

四、深入 Vue3 特性

4.1 Composition API

Composition API 是 Vue3 最重要的特性之一,它提供了一种更灵活的方式来组织和复用组件逻辑。通过 setup 函数(在 script setup 语法糖下隐式存在),可以将相关逻辑组合在一起。例如,实现一个简单的计数器功能:

<template><div><p>{{ count }}</p><button @click="increment">Increment</button></div>
</template><script setup>
import { ref } from 'vue';const count = ref(0);
const increment = () => {count.value++;
};
</script>

多个逻辑模块可以通过函数进行封装复用。例如,创建一个可复用的计数器逻辑函数 useCounter.js

import { ref } from 'vue';export const useCounter = () => {const count = ref(0);const increment = () => {count.value++;};return {count,increment};
};

在组件中使用这个逻辑函数:

<template><div><p>{{ counter.count }}</p><button @click="counter.increment">Increment</button></div>
</template><script setup>
import { useCounter } from './useCounter.js';const counter = useCounter();
</script>

4.2 Teleport

Teleport 是 Vue3 新增的功能,它允许将组件的一部分模板渲染到 DOM 的其他位置,而不是限制在父组件的 DOM 结构内。例如,在一个模态框组件中,希望模态框的遮罩层渲染到 body 元素下,而不是组件内部的某个元素下:

<template><Teleport to="body"><div class="modal - overlay"></div></Teleport><div class="modal - content"><p>Modal content</p></div>
</template><script setup>
import { Teleport } from 'vue';
</script>

4.3 Suspense

Suspense 用于处理异步组件的加载状态。当组件依赖异步数据时,可以使用 Suspense 来显示加载状态,直到数据加载完成。例如,有一个异步加载的组件 AsyncComponent.vue

<template><div><p>{{ data }}</p></div>
</template><script setup>
import { ref } from 'vue';
import { onMounted } from 'vue';const data = ref(null);
onMounted(async () => {const response = await fetch('https://example.com/api/data');const result = await response.json();data.value = result;
});
</script>

在父组件中使用 Suspense 包裹异步组件:

<template><Suspense><template #default><AsyncComponent /></template><template #fallback><p>Loading...</p></template></Suspense>
</template><script setup>
import { Suspense } from 'vue';
import AsyncComponent from './AsyncComponent.vue';
</script>

五、Vue3 与路由和状态管理

5.1 Vue Router

Vue Router 用于处理 Vue 应用的路由。在 Vue3 项目中使用 Vue Router,首先需要安装:

npm install vue - router@next

然后在项目中配置路由。例如,在 router/index.js 文件中:

import { createRouter, createWebHistory } from 'vue - router';
import Home from '../views/Home.vue';
import About from '../views/About.vue';const routes = [{path: '/',name: 'Home',component: Home},{path: '/about',name: 'About',component: About}
];const router = createRouter({history: createWebHistory(),routes
});export default router;

main.js 中引入并使用路由:

import { createApp } from 'vue';
import App from './App.vue';
import router from './router';const app = createApp(App);
app.use(router);
app.mount('#app');

在组件中使用路由链接和路由视图:

<template><div><router - link to="/">Home</router - link><router - link to="/about">About</router - link><router - view></router - view></div>
</template>

5.2 Vuex

Vuex 用于管理 Vue 应用的状态。在 Vue3 项目中安装 Vuex:

npm install vuex@next

在项目中创建 store/index.js 文件来配置 Vuex 存储:

import { createStore } from 'vuex';const store = createStore({state: {count: 0},mutations: {increment(state) {state.count++;}},actions: {incrementAsync({ commit }) {setTimeout(() => {commit('increment');}, 1000);}},getters: {doubleCount(state) {return state.count * 2;}}
});export default store;

main.js 中引入并使用 Vuex:

import { createApp } from 'vue';
import App from './App.vue';
import store from './store';const app = createApp(App);
app.use(store);
app.mount('#app');

在组件中使用 Vuex 的状态、mutation 和 action:

<template><div><p>{{ count }}</p><p>{{ doubleCount }}</p><button @click="increment">Increment</button><button @click="incrementAsync">Increment Async</button></div>
</template><script setup>
import { useStore } from 'vuex';const store = useStore();
const count = store.state.count;
const doubleCount = store.getters.doubleCount;
const increment = () => {store.commit('increment');
};
const incrementAsync = () => {store.dispatch('incrementAsync');
};
</script>

六、Vue3 性能优化

6.1 虚拟 DOM 优化

Vue3 对虚拟 DOM 算法进行了优化,减少了不必要的 DOM 操作。例如,在列表渲染时,通过 key 来唯一标识每个列表项,Vue 可以更准确地判断哪些元素需要更新,从而避免不必要的重新渲染。

<template><div><ul><li v - for="(item, index) in items" :key="item.id">{{ item.name }}</li></ul></div>
</template><script setup>
import { ref } from 'vue';const items = ref([{ id: 1, name: 'Apple' },{ id: 2, name: 'Banana' },{ id: 3, name: 'Cherry' }
]);
</script>

6.2 代码分割与懒加载

在大型应用中,使用代码分割和懒加载可以提高应用的加载性能。例如,对于路由组件,可以使用动态导入实现懒加载:

const routes = [{path: '/about',name: 'About',component: () => import('../views/About.vue')}
];

这样,只有当用户访问 /about 路由时,About.vue 组件才会被加载。

6.3 优化响应式数据

合理使用 refreactive,避免创建过多不必要的响应式数据。对于一些不需要响应式的纯计算数据,可以使用普通函数来处理,而不是将其包装成响应式数据。

七、Vue3 项目实战

7.1 项目需求分析

假设要开发一个简单的博客应用,具备文章列表展示、文章详情查看、添加文章等功能。

7.2 技术选型与架构设计

  • 技术选型:使用 Vue3、Vue Router、Vuex、Axios(用于 HTTP 请求)。
  • 架构设计:采用分层架构,视图层使用 Vue 组件构建用户界面,路由层处理页面导航,状态管理层使用 Vuex 管理应用状态,数据层通过 Axios 与后端 API 进行数据交互。

7.3 功能实现

  1. 文章列表:通过 Axios 从后端获取文章列表数据,使用 v - for 指令进行列表渲染。
  2. 文章详情:根据文章 ID 从后端获取文章详情数据,在详情页面展示。
  3. 添加文章:创建一个表单组件,用户填写文章信息后,通过 Axios 发送 POST 请求将数据保存到后端。

7.4 项目部署

将项目打包后,部署到服务器上。可以使用 Nginx 或其他 Web 服务器进行静态文件的托管。例如,在项目根目录下执行打包命令:

npm run build

然后将 dist 目录下的文件复制到服务器的相应目录,并配置 Nginx 进行访问。

八、总结

通过从基础语法到深入特性,再到与路由、状态管理结合以及性能优化和项目实战,全面介绍了 Vue3 的相关知识。Vue3 为前端开发带来了更高效、灵活的开发方式,掌握这些内容后,开发者能够更好地构建大型、复杂的前端应用。在实际开发中,还需要不断实践和探索,以解决各种实际问题,提升开发能力。


http://www.ppmy.cn/news/1572199.html

相关文章

DeepSeek API 调用 - Spring Boot 实现

DeepSeek API 调用 - Spring Boot 实现 1. 项目依赖 在 pom.xml 中添加以下依赖&#xff1a; <dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-webflux</artifactId></depe…

Android Studio:键值对存储sharedPreferences

一、了解 SharedPreferences SharedPreferences是Android的一个轻量级存储工具&#xff0c;它采用的存储结构是Key-Value的键值对方式&#xff0c;类似于Java的Properties&#xff0c;二者都是把Key-Value的键值对保存在配置文件中。不同的是&#xff0c;Properties的文件内容形…

基础算法 高精度运算 #大数加法

文章目录 题目链接题目解读完整代码参考 题目链接 题目解读 题目描述 输入两个正整数a,b&#xff0c;输出ab的值。 输入格式 两行&#xff0c;第一行a&#xff0c;第二行b。a和b的长度均小于1000位。 输出格式 一行&#xff0c;ab的值。 完整代码 #include<bits/stdc.h&…

Java 大视界 -- 大数据伦理与法律:Java 技术在合规中的作用与挑战(87)

&#x1f496;亲爱的朋友们&#xff0c;热烈欢迎来到 青云交的博客&#xff01;能与诸位在此相逢&#xff0c;我倍感荣幸。在这飞速更迭的时代&#xff0c;我们都渴望一方心灵净土&#xff0c;而 我的博客 正是这样温暖的所在。这里为你呈上趣味与实用兼具的知识&#xff0c;也…

DeepSeekApi对接流式输出异步聊天功能:基于Spring Boot和OkHttp的SSE应用实现

实现异步聊天功能&#xff1a;基于Spring Boot和OkHttp的SSE应用 在现代Web应用程序开发中&#xff0c;实时更新的能力对于增强用户体验至关重要。本文将详细介绍如何利用Spring Boot框架结合OkHttp库实现一个简单的异步聊天服务&#xff0c;该服务能够接收用户输入并通过Serv…

原生Three.js 和 Cesium.js 案例 。 智慧城市 数字孪生常用功能列表

对于大多数的开发者来言&#xff0c;看了很多文档可能遇见不到什么有用的&#xff0c;就算有用从文档上看&#xff0c;把代码复制到自己的本地大多数也是不能用的&#xff0c;非常浪费时间和学习成本&#xff0c; 尤其是three.js &#xff0c; cesium.js 这种难度较高&#xff…

【2025深度学习系列专栏大纲:深入探索与实践深度学习】

第一部分:深度学习基础篇 第1章:深度学习概览 1.1 深度学习的历史背景与发展轨迹 1.2 深度学习与机器学习、传统人工智能的区别与联系 1.3 深度学习的核心组件与概念解析 神经网络基础 激活函数的作用与类型 损失函数与优化算法的选择 1.4 深度学习框架简介与选择建议 第2…

如何在 Visual Studio Code 中使用 DeepSeek R1 和 Cline?

让我们面对现实吧&#xff1a;像 GitHub Copilot 这样的 AI 编码助手非常棒&#xff0c;但它们的订阅费用可能会在你的钱包里烧一个洞。进入 DeepSeek R1 — 一个免费的开源语言模型&#xff0c;在推理和编码任务方面可与 GPT-4 和 Claude 3.5 相媲美。将它与 Cline 配对&#…