选项式 API、生命周期与组件实例
组合式 API 是新项目的默认选择,但选项式 API 没死:老项目、简单组件、团队习惯都用它。而且 Vue 的底层概念(生命周期、实例)是共通的,读懂选项式才能读懂编译产物。这篇按"选项分类 + 生命周期 + 实例 API"组织,顺带处理 mixins 和 filters 两个历史包袱。
一、选项式 API 全景
Vue 组件选项按职责分七组:
| 分类 | 选项 | 说明 |
|---|---|---|
| 数据 | data、props、computed | 状态入口 |
| 方法 | methods | 事件处理与逻辑 |
| 生命周期 | created/mounted/updated 等 | 时机钩子 |
| 资源注册 | components、directives | 局部注册 |
| 组合 | mixins、extends、provide、inject | 代码复用与依赖注入 |
| DOM | template、render | 渲染来源 |
| 杂项 | name、inheritAttrs、compilerOptions、emits、expose | 边界配置 |
选项在组件里的执行顺序大致是:props → setup(如果有)→ beforeCreate → data 初始化 → inject → computed → methods → watch → created。这也是为什么 data 里能用 inject 的值,而 beforeCreate 里什么都还没有。
二、data 选项
export default {
data() {
return {
count: 0,
user: null,
list: []
};
},
created() {
this.user = await fetchUser(); // created 里 this 已可用
}
};2
3
4
5
6
7
8
9
10
11
12
- 必须是函数:返回新对象,保证每个实例独立。
- 返回对象的属性会被代理到实例:
this.count等价于this.$data.count。 - 别用箭头函数写
data():内部会用到this(调用时绑定实例),箭头函数拿不到。虽然多数人不这么写,但缩写时容易中招。 - Vue3 可以直接给 data 对象加新属性并保持响应式(Proxy 红利),但 TS 类型里不存在的字段编译期会报错——要么预声明,要么上 reactive。
- 和 setup 混用:setup 返回的对象与 data 的属性合并,重名时 setup 优先,别重名。
三、DOM 相关选项
3.1 template
- 字符串模板:
template: '<div>...</div>'(内部用双大括号插值),仅完整构建版(含编译器)可用。 - 选择器:
template: '#tpl'引用页面上<script type="text/x-template" id="tpl">的内容。 - SFC 的
<template>在构建时编译成 render 函数,运行时无需编译器——这是生产构建的标准路径,体积更小、无 CSP 限制。
3.2 render
手写渲染函数,优先级高于 template:
import { h } from 'vue';
export default {
render() {
return h('div', { class: 'box' }, [
this.msg,
this.$slots.default?.()
]);
}
};2
3
4
5
6
7
8
9
模板和 render 二选一。render 的完整 API 见《渲染函数、JSX、插件与 Web Components》。
3.3 el
el: '#app' 指定挂载点,等价于 this.$mount('#app')。只在根实例常用。
四、生命周期钩子
4.1 完整时序
创建阶段:beforeCreate → created
挂载阶段:beforeMount → mounted
更新阶段:beforeUpdate → updated
激活(KeepAlive):activated / deactivated
销毁阶段:beforeUnmount → unmounted
错误与调试:errorCaptured、renderTracked、renderTriggered2
3
4
5
6
beforeCreate 时 data、methods、computed 都未初始化,能用的只有 props 和 $options;created 起全部就绪但 DOM 不存在。SSR(服务端渲染)中 beforeMount/mounted 不会调用,只有 beforeCreate/created。
4.2 每个钩子干什么
| 钩子 | 典型用途 |
|---|---|
| beforeCreate | 几乎不用(要早期逻辑请用 setup) |
| created | 发首屏请求、初始化非 DOM 状态、订阅 store |
| beforeMount | 几乎不用 |
| mounted | DOM 操作、第三方库初始化、$refs 可用 |
| beforeUpdate | 获取更新前的 DOM 状态(滚动位置) |
| updated | 依赖新 DOM 的操作(注意可能多次触发) |
| activated | KeepAlive 缓存组件重新进入 |
| deactivated | KeepAlive 缓存组件离开 |
| beforeUnmount | 清定时器、解绑全局监听、取消请求 |
| unmounted | 收尾(DOM 已移除) |
| errorCaptured | 捕获子孙组件错误,返回 false 阻止向上传播 |
| renderTracked/renderTriggered | 开发调试:哪个依赖触发了渲染 |
请求放 created 还是 mounted?都能拿到数据,created 早一个 tick 发出请求,首屏更快;要用 $refs 里的 DOM 尺寸发请求(如按容器高度拉列表),放 mounted。
4.3 组合式对照表
| 选项式 | 组合式 |
|---|---|
| beforeCreate / created | setup() 本身 |
| beforeMount | onBeforeMount |
| mounted | onMounted |
| beforeUpdate | onBeforeUpdate |
| updated | onUpdated |
| activated / deactivated | onActivated / onDeactivated |
| beforeUnmount / unmounted | onBeforeUnmount / onUnmounted |
| errorCaptured | onErrorCaptured |
组合式没有 beforeCreate/created 的对应物,因为 setup 就是它们的合并。
五、资源与组合选项
5.1 components / directives
局部注册,只在本组件模板可用:
import MyIcon from './MyIcon.vue';
export default {
components: { MyIcon },
directives: { focus: { mounted(el) { el.focus(); } } }
};2
3
4
5
5.2 mixins:能用但不推荐
const loggerMixin = {
created() { console.log('组件创建', this.$options.name); },
methods: { log(msg) { console.log(msg); } }
};
export default { mixins: [loggerMixin] };2
3
4
5
合并规则:data/methods/computed 同名时组件优先;生命周期钩子合并成数组都执行,mixin 先跑;watch 的 handler 也合并执行。
mixins 的四个问题:
- 来源不清:
this.log()是从哪来的?要翻 mixin 定义。 - 命名冲突静默覆盖:大面积重构时最难查的 bug 之一。
- 隐式依赖:mixin 悄悄用了组件里恰好同名的 prop/data。
- TS 支持差:类型推导基本靠猜。
替代:组合式函数(composable)——同样的逻辑抽成 useLogger(),const { log } = useLogger(),来源显式、命名冲突编译期暴露、TS 友好。详见《组合式 API》。
5.3 extends
继承另一个组件,用途极少(扩写三方组件),优先级高于 mixins。新代码基本不用。
5.4 provide / inject
见《组件通信与透传》。选项式的 provide 是函数(能访问 this),组合式是直接调用 provide(key, val)。
六、杂项选项
| 选项 | 说明 |
|---|---|
name | DevTools 显示、KeepAlive include/exclude 匹配、递归组件自引用都靠它 |
inheritAttrs | 默认 true,透传自动挂根元素;false 后手动控制 |
emits | 声明事件,关掉同名原生事件透传 |
expose | 限制父组件通过 ref 能访问的实例属性 |
compilerOptions | 运行时编译选项,如 isCustomElement |
name 别忘了写:SFC 里可以从文件名推断,但 <script setup> + 构建产物压缩后不一定可靠,显式 defineOptions({ name: 'UserCard' }) 最稳——KeepAlive 的 include 匹配的就是它。
七、过滤器(已移除)
Vue2 的过滤器:
// Vue2:模板里 {{ price | currency }}
filters: { currency: v => '¥' + v.toFixed(2) }2
Vue3 完全移除,三条替代路线:
// 1. 计算属性/方法(首选)
const priceText = computed(() => '¥' + price.value.toFixed(2));
// 2. 全局属性挂工具函数
app.config.globalProperties.$fmt = { currency: v => '¥' + v.toFixed(2) };
// 模板:{{ $fmt.currency(price) }}
// 3. 需要复杂格式化(i18n、日期)用 vue-i18n 或 dayjs 直接调2
3
4
5
6
7
8
迁移时把所有 | 换成方法调用即可,注意过滤器参数语法(| filter(a, b))和方法调用(filter(a, b))其实一样。
八、实例 property
| 属性 | 值 | 说明 |
|---|---|---|
$data | data 对象 | 观测后的对象 |
$props | props 对象 | 父组件传入的 props |
$el | DOM 节点 | 根元素(多根组件是第一个) |
$options | 组件选项 | 含 name、自定义选项 |
$parent / $root | 实例 | 父/根实例,调试用 |
$refs | 对象 | 模板引用集合 |
$slots | 函数对象 | Vue3 里插槽是函数 |
$attrs | 对象 | 透传的 attribute 和监听 |
$listeners | — | 已移除,并入 $attrs |
$scopedSlots | — | 已移除,并入 $slots |
$vnode | vnode | 组件自身的占位节点 |
$nextTick | 函数 | DOM 更新后回调(实例属性) |
$parent/$root 只建议在调试和极端场景用,业务代码靠它们通信 = 拒绝组件化。
九、实例方法
9.1 $watch
实例级侦听,返回停止函数:
const stop = this.$watch('user.id', (newId, oldId) => reload(newId), {
immediate: true,
deep: false
});2
3
4
字符串路径形式 'user.id' 是选项式特有的简写,等价于 getter。注意和具名导出的 watch 是两套 API,能力一致。
9.2 $emit / $forceUpdate / $nextTick
this.$emit('submit', payload); // 派发事件
this.$forceUpdate(); // 强制重渲染(几乎不该用)
this.$nextTick(() => { /* DOM 已更新 */ });2
3
$forceUpdate 只在"直接改了非响应式数据"的兜底场景出现,用了它说明状态管理有问题,先查响应式丢失。
nextTick 的常见用法:v-if 切换后测量新元素高度、等列表渲染完滚动到底部:
this.showPanel = true;
this.$nextTick(() => { this.panelHeight = this.$refs.panel.offsetHeight; });2
十、FAQ
Q:created 和 setup 谁先执行?
A:setup 在 beforeCreate 之前就执行完了,所以 setup 里访问不到 data/methods(它们还没初始化),但可以访问 props。
Q:updated 里又改了数据,会死循环吗?
A:不会死循环,但会持续触发更新,性能雪崩。更新后副作用用 watch(..., { flush: 'post' }) 或 watchPostEffect,语义更精确。
Q:mounted 在子组件还是父组件先执行?
A:子组件先 mounted,父组件后 mounted(挂载是自底向上)。created 相反,父先子后(自顶向下)。排查"父组件里拿子组件 ref 为空"时记住这个。
Q:mixins 迁移成组合式函数有什么套路?
A:按功能把 mixin 的 data/methods/computed 分成若干 useXxx 函数,在 setup 里显式调用并解构。同名冲突迁移时会暴露出来,正好逐个裁决。
Q:errorCaptured 能捕获异步错误吗?
A:不能,它只捕获渲染/生命周期/事件处理器里的同步错误。异步错误用 app.config.errorHandler 或 try/catch。
