Vue 3 核心 API 概览
Vue 3 引入了 Composition API 作为其核心特性之一,同时保留了 Options API。以下是 Vue 3 的主要核心 API:
1. 应用实例 API
createApp
import { createApp } from 'vue'
const app = createApp({ /* 根组件选项 */ })
应用配置
app.config
.errorHandler = (err, vm, info) => { /* 错误处理 */ }
.warnHandler = (msg, vm, trace) => { /* 警告处理 */ }
.globalProperties = { /* 全局属性 */ }
应用方法
app.mount('#app') // 挂载应用
app.unmount() // 卸载应用
app.component() // 注册全局组件
app.directive() // 注册全局指令
app.use() // 使用插件
2. 组合式 API (Composition API)
响应式基础
import { ref, reactive, computed, watch, watchEffect } from 'vue'
// 基本响应式
const count = ref(0) // 适用于基本类型
const state = reactive({ count: 0 }) // 适用于对象
// 计算属性
const doubleCount = computed(() => count.value * 2)
// 侦听器
watch(count, (newVal, oldVal) => { /* ... */ })
watchEffect(() => { console.log(count.value) }) // 自动追踪依赖
生命周期钩子
import { onMounted, onUpdated, onUnmounted } from 'vue'
setup() {
onMounted(() => { /* ... */ })
onUpdated(() => { /* ... */ })
onUnmounted(() => { /* ... */ })
// 其他:onBeforeMount, onBeforeUpdate, onBeforeUnmount, onErrorCaptured
}
依赖注入
import { provide, inject } from 'vue'
// 祖先组件
setup() {
provide('theme', 'dark')
}
// 后代组件
setup() {
const theme = inject('theme', 'light' /* 默认值 */)
}
3. 响应式工具函数
import {
isRef, unref, toRef, toRefs,
isProxy, isReactive, isReadonly,
markRaw, shallowRef, shallowReactive, readonly
} from 'vue'
// 转换和检查
const unwrapped = unref(maybeRef) // 解包ref
const objRef = toRef(object, 'key') // 对象属性转为ref
const refs = toRefs(reactiveObj) // 将reactive对象转换为普通对象,每个属性都是ref
// 只读和浅响应式
const readOnlyState = readonly(state)
const shallow = shallowReactive({ nested: { ... } }) // 只响应第一层
4. 组件相关 API
defineComponent
import { defineComponent } from 'vue'
export default defineComponent({
// 组件选项
})
defineAsyncComponent
(异步组件)
const AsyncComp = defineAsyncComponent(() => import('./AsyncComp.vue'))
模板引用
import { ref, onMounted } from 'vue'
setup() {
const root = ref(null)
onMounted(() => {
console.log(root.value) // 获取DOM元素或组件实例
})
return { root }
}
5. 内置组件
<template>
<Teleport to="body">...</Teleport> // 传送组件
<Suspense> // 异步组件处理
<template #default>...</template>
<template #fallback>Loading...</template>
</Suspense>
<KeepAlive>...</KeepAlive> // 缓存组件
<Transition>...</Transition> // 过渡动画
</template>
6. 自定义渲染器 API
import { createRenderer } from '@vue/runtime-core'
const { render, createApp } = createRenderer({
// 自定义渲染逻辑
})
7. 服务端渲染 API
import { renderToString } from '@vue/server-renderer'
const html = await renderToString(app)
8. TypeScript 支持
Vue 3 完全使用 TypeScript 重写,提供了良好的类型支持:
interface User {
id: number
name: string
}
const user = ref<User>({ id: 1, name: 'John' })
这些核心 API 构成了 Vue 3 的基础功能,使得开发更加灵活和高效。Composition API 特别适合复杂组件的逻辑组织和复用。