Vue2 和 Vue3 所有区别(完整版、面试+开发必看)
我给你整理成最清晰、最全面、不啰嗦 的版本,覆盖架构、语法、API、响应式、生命周期、组件、工程化全部差异,你直接保存这一份就够了。
一、最核心、最根本的区别
-
Vue2 使用 Options API(选项式)
按 data / methods / computed / watch 分类写代码
→ 代码量大时逻辑分散,难维护
-
Vue3 主推 Composition API(组合式)
按业务功能 聚合代码
→ 逻辑清晰、复用性强、适合大型项目
→ 搭配
<script setup>语法更简洁
二、响应式原理区别
| 特性 | Vue2 | Vue3 |
|---|---|---|
| 实现 | Object.defineProperty() |
Proxy 代理 |
| 监听能力 | 只能监听对象已有属性,数组下标修改不响应 | 监听整个对象,支持数组、新增属性、Map/Set |
| 性能 | 一般 | 更快,减少不必要响应 |
| this | 必须用 this | 没有 this |
一句话:
Vue2 响应式有缺陷,Vue3 用 Proxy 彻底解决。
三、生命周期区别
Vue2
beforeCreate → created → beforeMount → mounted → beforeUpdate → updated → beforeDestroy → destroyed
Vue3(组合式)
setup() = beforeCreate + created
其他钩子前面加 on:
- onMounted
- onUpdated
- onUnmounted(替代 destroyed)
四、模板语法区别
Vue2
必须有一个根节点
vue
<template>
<div>
<div></div>
</div>
</template>
Vue3
支持多根节点
vue
<template>
<div></div>
<div></div>
</template>
五、数据定义(最常用)
Vue2
js
data() {
return {
count: 0
}
}
Vue3
js
import { ref, reactive } from 'vue'
const count = ref(0)
const user = reactive({ name: 'zs' })
六、方法、计算属性、监听
Vue2
js
methods: {
add() {}
},
computed: {
double() {}
},
watch: {
count() {}
}
Vue3
js
import { ref, computed, watch } from 'vue'
const add = () => {}
const double = computed(() => count.value * 2)
watch(count, () => {})
七、父子通信
Vue2
- props
- $emit
- .sync 修饰符
Vue3
- defineProps
- defineEmits
- v-model:xxx 替代 .sync
- 支持多个 v-model
八、全局 API 变化(重要)
Vue2
js
import Vue from 'vue'
Vue.use(xxx)
new Vue({})
Vue3
js
import { createApp } from 'vue'
const app = createApp(App)
app.use(xxx)
避免全局污染。
九、路由变化(vue-router)
Vue2
js
new VueRouter({})
Vue3
js
import { createRouter, createWebHistory } from 'vue-router'
十、Vuex → Pinia
Vue2 用 Vuex
Vue3 官方推荐 Pinia
更简洁、无 mutations、支持TS、组合式友好
十一、TypeScript 支持
- Vue2 支持差
- Vue3 原生 TS 支持,全部用 TS 重写
十二、性能提升
- 打包体积更小
- 渲染速度提升 50%
- 服务端渲染更快
- Tree-shaking 更好
十三、废弃的 API(Vue3 不能用)
- on、on、on、off、$once
- filters 过滤器
- $children
- .sync 修饰符
- 全局 Vue 构造函数
十四、一句话总结所有区别
- Vue2 是选项式,Vue3 是组合式
- Vue2 用 defineProperty,Vue3 用 Proxy
- Vue2 必须单根节点,Vue3 支持多根
- Vue2 有 this,Vue3 没有 this
- Vue2 有.sync,Vue3 用 v-model:xxx
- Vue2 用 Vuex,Vue3 用 Pinia
- Vue2 TS 差,Vue3 TS 友好
- Vue3 性能更强、代码更简洁、大型项目更好维护