Vue 3 是 Vue.js 框架的重大升级,带来了许多新特性和性能优化。以下是 Vue 3 的主要新特性详解:
一、Composition API
Vue 3 引入了 Composition API,旨在解决 Options API 在复杂组件中逻辑复用和代码组织的问题。通过 setup()
函数和响应式 API,开发者可以更灵活地组合逻辑。
1. setup()
函数
- 新的组件选项,在组件初始化阶段执行。
- 替代了 Vue 2 中的
data
、methods
、computed
等选项。 - 接收
props
和context
参数,返回的对象会暴露给模板使用。
import { ref } from 'vue';
export default {setup(props) {const count = ref(0);const increment = () => count.value++;return { count, increment };}
};
2. 响应式 API
ref
:包装基本类型数据为响应式对象(通过.value
访问)。reactive
:将对象转换为响应式对象(深度响应)。computed
:创建计算属性。watch
和watchEffect
:监听响应式数据的变化。
import { reactive, watchEffect } from 'vue';
const state = reactive({ count: 0 });
watchEffect(() => {console.log(`Count is: ${state.count}`);
});
3. 逻辑复用
- 通过自定义函数封装可复用逻辑(类似 React Hooks)。
// useCounter.js
import { ref } from 'vue';
export function useCounter() {const count = ref(0);const increment = () => count.value++;return { count, increment };
}
二、性能优化
1. 基于 Proxy 的响应式系统
- Vue 3 使用
Proxy
替代Object.defineProperty
,支持:- 监听数组变化(无需重写数组方法)。
- 动态添加/删除属性。
- 更好的性能表现。
2. Tree-shaking 支持
- 按需引入 API,未使用的功能不会被打包到生产环境,减少代码体积。
3. 编译时优化
- 静态节点提升(Static Hoisting):将静态节点提升到渲染函数外部,避免重复渲染。
- 补丁标志(Patch Flags):标记动态节点类型,优化虚拟 DOM 的 diff 过程。
- 缓存事件处理函数:减少不必要的更新。
三、新组件特性
1. Fragment(片段)
- 组件支持多根节点,无需包裹一个父元素。
<template><header></header><main></main><footer></footer>
</template>
2. Teleport(传送门)
- 将组件渲染到 DOM 中的任意位置(如全局弹窗)。
<template><button @click="showModal">打开弹窗</button><Teleport to="body"><Modal v-if="isShow" /></Teleport>
</template>
3. Suspense(异步组件)
- 优雅地处理异步组件加载状态。
<template><Suspense><template #default><AsyncComponent /></template><template #fallback><div>Loading...</div></template></Suspense>
</template>
四、TypeScript 支持
- Vue 3 使用 TypeScript 重写,提供更完善的类型推断。
- 组件选项(如
props
、emits
)支持类型声明。
interface Props {title: string;
}
export default defineComponent({props: {title: {type: String as PropType<Props['title']>,required: true}}
});
五、其他改进
1. 全局 API 调整
- 使用
createApp
代替new Vue()
,避免全局配置污染。
import { createApp } from 'vue';
const app = createApp(App);
app.use(router).mount('#app');
2. 自定义渲染器
- 允许开发者自定义渲染逻辑(如 WebGL、Canvas 渲染)。
3. 多个 v-model
绑定
- 支持在单个组件上绑定多个
v-model
。
<ChildComponent v-model:name="name" v-model:age="age" />
4. 生命周期调整
beforeDestroy
和destroyed
更名为beforeUnmount
和unmounted
。- 新增
renderTracked
和renderTriggered
用于调试响应式依赖。
六、生态适配
- Vue Router 4:支持 Vue 3 的路由库。
- Vuex 4:状态管理库适配。
- Vite:新一代构建工具,提供极速开发体验。
- vue: 脚手架https://cli.vuejs.org/config/
- vue3文档: https://cn.vuejs.org/guide/introduction.html
总结
Vue 3 通过 Composition API 提升了代码组织和复用能力,通过 Proxy 和编译优化显著提升了性能,并引入了 Fragment、Teleport 等新特性简化开发。同时,完善的 TypeScript 支持使其更适合大型项目。如需迁移 Vue 2 项目,可使用官方迁移工具逐步升级。