← 返回完整题库
vue.js困难

Vue3.0 所采用的 Composition Api 与 Vue2.x 使用的 Options Api 有什么不同?

参考答案

对比

| 维度 | Options API | Composition API |
|---|---|---|
| 组织方式 | 按选项类型分块:data/computed/methods/watch/生命周期 | 按功能逻辑分块:一个功能的 ref/computed/watch 放一起 |
| 复用 | mixins(来源不明、命名冲突、隐式依赖) | 组合式函数 useXxx(),显式返回、可嵌套、可类型推导 |
| 类型支持 | this 上成员靠运行时合并,TS 支持弱 | 普通变量与函数,TS 完整推导 |
| this | 依赖 this,绑定上下文易出错 | 无 this,纯函数式 |
| 逻辑可读性 | 复杂组件里一个功能散落多处 | 高内聚,改功能只看一处 |
| 生命周期 | 选项钩子 | onMounted/onUnmounted 等组合式函数,可写在任意位置 |
| 逻辑复用边界 | mixin 全局污染 | effectScope 可统一管理一组副作用的生命周期 |
| 上手成本 | 低,约定清晰 | 略高,需理解 ref/reactive/解构陷阱 |
| tree-shaking | 全量 API | 按需 import,未用不打包 |
| 适用规模 | 中小型、简单组件 | 中大型、复杂逻辑、需要复用与测试 |

具体差异举例

// Options
export default {
  data() { return { list: [], loading: false } },
  computed: { total() { return this.list.length } },
  watch: { keyword() { this.fetch() } },
  methods: { async fetch() { ... } },
  mounted() { this.fetch() },
}

// Composition
const list = ref([])
const loading = ref(false)
const total = computed(() => list.value.length)
async function fetchList() { ... }
watch(keyword, fetchList)
onMounted(fetchList)

结论

  • Composition API 不是「更高级」,而是更适合组织复杂逻辑与复用;
  • Options API 并未废弃,Vue 3 仍完整支持,两者可混用;
  • 实际项目常见:<script setup> + 组合式函数为主,少量 Options 组件(老代码/第三方集成)。

本题来自 计算机知识面试题库,共 921 道题。