
一、Vue3 简介
Vue.js 是一款流行的 JavaScript 前端框架,用于构建用户界面。Vue3 作为 Vue.js 的重大升级版本,带来了诸多性能提升和新特性。它采用了 Proxy 实现数据响应式系统,优化了虚拟 DOM 算法,使得应用在运行时更加高效。同时,Composition API 的引入为组件逻辑复用和代码组织提供了更灵活的方式,让开发者能够更优雅地处理复杂业务逻辑。
二、环境搭建
2.1 安装 Node.js
Vue3 项目基于 Node.js 运行,首先需要从 Node.js 官网 下载并安装最新版本的 Node.js。安装完成后,在命令行中输入 node -v
和 npm -v
检查是否安装成功,这两个命令会分别输出版本号。
2.2 创建 Vue3 项目
使用 Vue CLI 是创建 Vue3 项目最便捷的方式。如果尚未安装 Vue CLI,可以通过以下命令进行全局安装:
bash
npm install -g @vue/cli
安装完成后,使用以下命令创建一个新的 Vue3 项目:
bash
vue create my - vue3 - project
在创建过程中,会提示选择预设配置,可根据项目需求选择默认配置或手动选择特性。例如,选择手动配置可以勾选路由、状态管理等功能。
三、Vue3 基础语法
3.1 模板语法
Vue3 的模板语法与 Vue2 基本相似,但在一些细节上有所改进。例如,插值表达式依然使用 {``{ }}
,可以在其中插入变量、表达式:
html
<template>
<div>
<p>{{ message }}</p>
<p>{{ 1 + 2 }}</p>
</div>
</template>
<script setup>
import { ref } from 'vue';
const message = ref('Hello, Vue3!');
</script>
指令方面,常见的 v - if
、v - for
、v - bind
(缩写为 :
)、v - on
(缩写为 @
)等依然可用。例如,使用 v - if
进行条件渲染:
html
<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
进行列表渲染:
html
<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 中,主要使用 ref
和 reactive
来创建响应式数据。
ref
用于创建一个包含响应式数据的引用,基本数据类型和复杂数据类型都适用。例如:
html
<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
用于创建一个响应式的对象或数组。例如:
html
<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
:
html
<template>
<div>
<p>{{ msg }}</p>
</div>
</template>
<script setup>
import { ref } from 'vue';
const msg = ref('This is a sub - component');
</script>
在父组件中使用该子组件:
html
<template>
<div>
<MyComponent />
</div>
</template>
<script setup>
import MyComponent from './MyComponent.vue';
</script>
组件之间可以通过 props 传递数据,例如在父组件中传递数据给子组件:
html
<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:
html
<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
语法糖下隐式存在),可以将相关逻辑组合在一起。例如,实现一个简单的计数器功能:
html
<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
:
javascript
import { ref } from 'vue';
export const useCounter = () => {
const count = ref(0);
const increment = () => {
count.value++;
};
return {
count,
increment
};
};
在组件中使用这个逻辑函数:
html
<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
元素下,而不是组件内部的某个元素下:
html
<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
:
html
<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
包裹异步组件:
html
<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,首先需要安装:
bash
npm install vue - router@next
然后在项目中配置路由。例如,在 router/index.js
文件中:
javascript
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
中引入并使用路由:
javascript
import { createApp } from 'vue';
import App from './App.vue';
import router from './router';
const app = createApp(App);
app.use(router);
app.mount('#app');
在组件中使用路由链接和路由视图:
html
<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:
bash
npm install vuex@next
在项目中创建 store/index.js
文件来配置 Vuex 存储:
javascript
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:
javascript
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:
html
<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 可以更准确地判断哪些元素需要更新,从而避免不必要的重新渲染。
html
<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 代码分割与懒加载
在大型应用中,使用代码分割和懒加载可以提高应用的加载性能。例如,对于路由组件,可以使用动态导入实现懒加载:
javascript
const routes = [
{
path: '/about',
name: 'About',
component: () => import('../views/About.vue')
}
];
这样,只有当用户访问 /about
路由时,About.vue
组件才会被加载。
6.3 优化响应式数据
合理使用 ref
和 reactive
,避免创建过多不必要的响应式数据。对于一些不需要响应式的纯计算数据,可以使用普通函数来处理,而不是将其包装成响应式数据。
七、Vue3 项目实战
7.1 项目需求分析
假设要开发一个简单的博客应用,具备文章列表展示、文章详情查看、添加文章等功能。
7.2 技术选型与架构设计
- 技术选型:使用 Vue3、Vue Router、Vuex、Axios(用于 HTTP 请求)。
- 架构设计:采用分层架构,视图层使用 Vue 组件构建用户界面,路由层处理页面导航,状态管理层使用 Vuex 管理应用状态,数据层通过 Axios 与后端 API 进行数据交互。
7.3 功能实现
- 文章列表 :通过 Axios 从后端获取文章列表数据,使用
v - for
指令进行列表渲染。 - 文章详情:根据文章 ID 从后端获取文章详情数据,在详情页面展示。
- 添加文章:创建一个表单组件,用户填写文章信息后,通过 Axios 发送 POST 请求将数据保存到后端。
7.4 项目部署
将项目打包后,部署到服务器上。可以使用 Nginx 或其他 Web 服务器进行静态文件的托管。例如,在项目根目录下执行打包命令:
bash
npm run build
然后将 dist
目录下的文件复制到服务器的相应目录,并配置 Nginx 进行访问。
八、总结
通过从基础语法到深入特性,再到与路由、状态管理结合以及性能优化和项目实战,全面介绍了 Vue3 的相关知识。Vue3 为前端开发带来了更高效、灵活的开发方式,掌握这些内容后,开发者能够更好地构建大型、复杂的前端应用。在实际开发中,还需要不断实践和探索,以解决各种实际问题,提升开发能力。