Vue 3 全局 API 详解 && Vue 3 选项式 API 详解

(一)、Vue 3 全局 API 详解

Vue 3 对全局 API 进行了革命性重构,从挂载在 Vue 对象上改为按需导入,实现了更优的树摇(Tree-shaking)支持。以下是核心全局 API 的分类解析与对比:

一、应用配置类 API
APIVue 2 写法Vue 3 写法功能说明
全局配置Vue.config.xxx = ...app.config.xxx = ...配置生产环境提示、错误处理等
编译选项Vue.config.compilerOptionsapp.config.compilerOptions自定义编译规则(如标签白名单)
性能追踪Vue.config.performanceapp.config.performance开启性能标记(需浏览器支持)

示例

// Vue 3 配置生产环境提示
import { createApp } from 'vue';
const app = createApp({});
app.config.errorHandler = (err) => {
  console.error('全局错误:', err);
};
二、组件注册类 API
APIVue 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
APIVue 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
APIVue 2 写法Vue 3 写法功能说明
扩展工具Vue.extend(options)defineComponent(options)创建组件构造器
标记为组件Vue.componentdefineComponent明确标记选项为组件
标记为自定义元素Vue.config.ignoredElementsapp.config.compilerOptions.isCustomElement标记原生自定义元素

示例

// Vue 3 使用 defineComponent
import { defineComponent } from 'vue';
export default defineComponent({
  name: 'MyComponent',
  props: {
    title: String
  }
});
五、服务端渲染(SSR)类 API
APIVue 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.compilerOptionsapp.config.compilerOptions从静态配置改为应用级配置
七、最佳实践建议
  1. 按需导入

    // 正确方式:仅导入需要的 API
    import { createApp, ref } from 'vue';
    // 错误方式:导入整个 Vue 对象
    // import Vue from 'vue';
    
  2. 多应用支持

    // 创建独立应用实例
    const app1 = createApp(App1);
    const app2 = createApp(App2);
    app1.mount('#app1');
    app2.mount('#app2');
    
  3. 类型提示

    // 在 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.definePropertyProxy更优的性能和更全面的拦截
生命周期钩子8 个核心钩子10 个核心钩子 + 2 个调试钩子新增 onRenderTracked 等调试钩子
混合冲突需手动处理命名冲突自动合并策略优化减少混合开发时的命名冲突风险
自定义选项需通过插件手动解析内置支持更简洁的自定义选项扩展方式
八、最佳实践建议
  1. 响应式数据初始化

    // 正确方式:在 data() 中返回所有响应式数据
    data() {
      return {
        count: 0,
        list: []
      };
    }
    
  2. 计算属性缓存

    // 避免在计算属性中执行副作用操作
    computed: {
      filteredList() {
        return this.list.filter(item => item.active);
      }
    }
    
  3. 侦听器优化

    // 使用对象语法配置深度侦听和立即执行
    watch: {
      searchQuery: {
        handler(newVal) {
          this.debouncedSearch(newVal);
        },
        immediate: true,
        deep: true
      }
    }
    

通过掌握选项式 API 的核心特性,您可以在 Vue 3 中继续使用熟悉的开发模式,同时享受响应式系统升级带来的性能提升。对于复杂逻辑组件,可结合组合式 API 实现更好的逻辑复用。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值