(一)、Vue 3 全局 API 详解
Vue 3 对全局 API 进行了革命性重构,从挂载在 Vue
对象上改为按需导入,实现了更优的树摇(Tree-shaking)支持。以下是核心全局 API 的分类解析与对比:
一、应用配置类 API
API | Vue 2 写法 | Vue 3 写法 | 功能说明 |
---|---|---|---|
全局配置 | Vue.config.xxx = ... | app.config.xxx = ... | 配置生产环境提示、错误处理等 |
编译选项 | Vue.config.compilerOptions | app.config.compilerOptions | 自定义编译规则(如标签白名单) |
性能追踪 | Vue.config.performance | app.config.performance | 开启性能标记(需浏览器支持) |
示例:
// Vue 3 配置生产环境提示
import { createApp } from 'vue';
const app = createApp({});
app.config.errorHandler = (err) => {
console.error('全局错误:', err);
};
二、组件注册类 API
API | Vue 2 写法 | Vue 3 写法 | 功能说明 |
---|---|---|---|
全局组件 | Vue.component('name', component) | app.component('name', component) | 注册全局可用组件 |
全局指令 | Vue.directive('name', directive) | app.directive('name', directive) | 注册全局指令 |
全局混合 | Vue.mixin(mixin) | app.mixin(mixin) | 注册全局混合(慎用) |
示例:
// Vue 3 注册全局组件
import { createApp } from 'vue';
import MyComponent from './MyComponent.vue';
const app = createApp({});
app.component('MyComponent', MyComponent);
三、插件安装类 API
API | Vue 2 写法 | Vue 3 写法 | 功能说明 |
---|---|---|---|
插件安装 | Vue.use(plugin) | app.use(plugin) | 安装插件(如 Vue Router、Pinia) |
示例:
// Vue 3 安装路由插件
import { createApp } from 'vue';
import { createRouter } from 'vue-router';
import App from './App.vue';
const router = createRouter({ /* 配置 */ });
const app = createApp(App);
app.use(router);
app.mount('#app');
四、工具函数类 API
API | Vue 2 写法 | Vue 3 写法 | 功能说明 |
---|---|---|---|
扩展工具 | Vue.extend(options) | defineComponent(options) | 创建组件构造器 |
标记为组件 | Vue.component | defineComponent | 明确标记选项为组件 |
标记为自定义元素 | Vue.config.ignoredElements | app.config.compilerOptions.isCustomElement | 标记原生自定义元素 |
示例:
// Vue 3 使用 defineComponent
import { defineComponent } from 'vue';
export default defineComponent({
name: 'MyComponent',
props: {
title: String
}
});
五、服务端渲染(SSR)类 API
API | Vue 2 写法 | Vue 3 写法 | 功能说明 |
---|---|---|---|
创建渲染器 | new VueSSRServerRenderer() | createSSRApp | 创建服务端渲染应用实例 |
流式渲染 | renderer.renderToStream() | renderToString | 流式输出 HTML 字符串 |
示例:
// Vue 3 服务端渲染
import { createSSRApp } from 'vue';
import App from './App.vue';
export function render(url) {
const app = createSSRApp(App);
return renderToString(app);
}
六、Vue 2 vs Vue 3 全局 API 迁移对比
场景 | Vue 2 代码 | Vue 3 代码 | 变化说明 |
---|---|---|---|
全局组件注册 | Vue.component(...) | app.component(...) | 从静态挂载改为实例方法 |
混合使用 | Vue.mixin(...) | app.mixin(...) | 作用域从全局变为应用实例级 |
自定义指令 | Vue.directive(...) | app.directive(...) | 语法一致,但作用域不同 |
编译配置 | Vue.config.compilerOptions | app.config.compilerOptions | 从静态配置改为应用级配置 |
七、最佳实践建议
-
按需导入:
// 正确方式:仅导入需要的 API import { createApp, ref } from 'vue'; // 错误方式:导入整个 Vue 对象 // import Vue from 'vue';
-
多应用支持:
// 创建独立应用实例 const app1 = createApp(App1); const app2 = createApp(App2); app1.mount('#app1'); app2.mount('#app2');
-
类型提示:
// 在 TypeScript 中使用 import type { App } from 'vue'; export default { install(app: App) { app.directive('focus', { /* 指令逻辑 */ }); } };
通过掌握 Vue 3 的全局 API 体系,您可以更灵活地构建模块化应用,同时享受 Tree-shaking 带来的体积优化。在迁移 Vue 2 项目时,重点关注组件注册和插件安装方式的变更,可显著降低迁移成本。
(二)、 Vue 3 选项式 API 详解
Vue 3 虽以 组合式 API 为主推特性,但 选项式 API 仍被完整保留并优化,成为两种并行的开发范式。以下是选项式 API 的核心解析,涵盖数据响应式、生命周期、组件通信等关键模块:
一、选项式 API 核心结构
export default {
// 数据响应式
data() {
return { count: 0 };
},
// 计算属性
computed: {
doubleCount() {
return this.count * 2;
}
},
// 方法
methods: {
increment() {
this.count++;
}
},
// 侦听器
watch: {
count(newVal, oldVal) {
console.log(`Count changed from ${oldVal} to ${newVal}`);
}
},
// 生命周期钩子
mounted() {
console.log('Component mounted');
}
};
二、数据响应式系统
1. data()
函数
- 返回值:必须为函数,返回初始数据对象
- 响应式原理:Vue 3 使用
Proxy
替代 Vue 2 的Object.defineProperty
- 对比 Vue 2:
// Vue 2 需显式声明响应式 data: { count: 0 } // Vue 3 保持相同语法,但底层实现优化
2. computed
计算属性
- 特点:缓存依赖值,仅在相关响应式依赖变化时重新计算
- 写法对比:
// Vue 2/3 通用写法 computed: { fullName() { return `${this.firstName} ${this.lastName}`; } }
3. watch
侦听器
- 深度侦听:
watch: { user: { handler(newVal) { console.log('User data changed:', newVal); }, deep: true, // 深度侦听对象内部变化 immediate: true // 立即执行一次 } }
三、生命周期钩子(完整列表)
钩子函数 | 执行时机 | 典型用途 |
---|---|---|
beforeCreate | 实例初始化后,数据观测前 | 极少使用 |
created | 实例创建完成,数据观测完成 | 发起异步请求 |
beforeMount | 模板编译前 | 极少使用 |
mounted | 模板挂载后 | 操作 DOM、订阅事件 |
beforeUpdate | 数据更新时,虚拟 DOM 重新渲染前 | 极少使用 |
updated | 虚拟 DOM 重新渲染后 | 操作更新后的 DOM |
beforeUnmount | 组件卸载前 | 清除定时器、取消网络请求 |
unmounted | 组件卸载后 | 最终清理工作 |
errorCaptured | 组件树中发生错误时 | 错误日志记录、降级处理 |
四、组件通信
1. Props 向下传递
// 父组件
<ChildComponent :message="parentMsg" />
// 子组件声明
export default {
props: {
message: {
type: String,
required: true
}
}
}
2. $emit
向上触发
// 子组件
this.$emit('custom-event', payload);
// 父组件监听
<ChildComponent @custom-event="handleEvent" />
3. Provide/Inject 跨层级
// 祖先组件
export default {
provide() {
return {
theme: this.theme
};
}
}
// 后代组件
export default {
inject: ['theme']
}
五、混合(Mixin)
1. 基础用法
// mixin.js
export default {
data() {
return { sharedState: 'mixin data' };
},
methods: {
mixinMethod() {
console.log('Mixin method called');
}
}
}
// 组件中使用
import mixin from './mixin.js';
export default {
mixins: [mixin],
created() {
this.mixinMethod(); // 输出: Mixin method called
}
}
2. 选项合并策略
- 生命周期钩子:合并为数组,按顺序执行
- 数据对象:组件选项覆盖混合选项
- 方法/计算属性:组件选项覆盖混合选项
六、自定义选项
// 定义自定义选项
export default {
myOption: 'custom value',
created() {
console.log(this.myOption); // 输出: custom value
}
}
// 通过插件扩展
app.mixin({
created() {
if (this.$options.myOption) {
console.log('Custom option detected:', this.$options.myOption);
}
}
});
七、Vue 2 vs Vue 3 选项式 API 差异
特性 | Vue 2 行为 | Vue 3 行为 | 变化说明 |
---|---|---|---|
响应式系统 | Object.defineProperty | Proxy | 更优的性能和更全面的拦截 |
生命周期钩子 | 8 个核心钩子 | 10 个核心钩子 + 2 个调试钩子 | 新增 onRenderTracked 等调试钩子 |
混合冲突 | 需手动处理命名冲突 | 自动合并策略优化 | 减少混合开发时的命名冲突风险 |
自定义选项 | 需通过插件手动解析 | 内置支持 | 更简洁的自定义选项扩展方式 |
八、最佳实践建议
-
响应式数据初始化:
// 正确方式:在 data() 中返回所有响应式数据 data() { return { count: 0, list: [] }; }
-
计算属性缓存:
// 避免在计算属性中执行副作用操作 computed: { filteredList() { return this.list.filter(item => item.active); } }
-
侦听器优化:
// 使用对象语法配置深度侦听和立即执行 watch: { searchQuery: { handler(newVal) { this.debouncedSearch(newVal); }, immediate: true, deep: true } }
通过掌握选项式 API 的核心特性,您可以在 Vue 3 中继续使用熟悉的开发模式,同时享受响应式系统升级带来的性能提升。对于复杂逻辑组件,可结合组合式 API 实现更好的逻辑复用。