大家好,我是大华!这篇我们来讲解Vue2和Vue3的核心区别在哪里?
Vue3是Vue2的升级版,不仅更快,还更好用。它解决了Vue2中一些让人头疼的问题,比如动态添加属性不响应、组件必须包在一个根元素里等等。
下面通过10个常见的对比例子,让你快速看懂Vue3到底新在哪儿、好在哪儿。
1. 响应式系统:Object.defineProperty vs Proxy
Vue 2 无法监听动态添加的属性(除非用 Vue.set);Vue 3 可以直接响应。
js
// Vue 2 不会触发更新
this.obj.newProp = 'hello'
// Vue 2 正确方式
this.$set(this.obj, 'newProp', 'hello')
// Vue 3 直接赋值即可响应
this.obj.newProp = 'hello'
2. Composition API(组合式 API)
html
export default {
data() {
return { count: 0 }
},
methods: {
increment() {
this.count++
}
}
}
import { ref } from 'vue'
const count = ref(0)
const increment = () => count.value++
3. TypeScript 支持
ts
// Vue 3 + TypeScript(能更好的支持)
interface Props {
msg: string
}
const props = defineProps()
Vue 2 虽可通过 vue-class-component 或 vue-property-decorator 支持 TS,但配置复杂且类型推导弱。
4. Fragment(多根节点)
html
<header>Header</header>
<main>Main</main>
<header>Header</header>
<main>Main</main>
5. Teleport(传送门)
将 modal 渲染到 body 下,避免样式嵌套问题
html
Open Modal
<div class="modal">
<p>Hello from Teleport!</p>
Close
</div>
import { ref } from 'vue'
const open = ref(false)
Vue 2 需手动操作 DOM 或使用第三方库(如 portal-vue)。
6. Suspense(异步组件加载)
html
const res = await fetch('/api/data')
const data = await res.json()
<div>{{ data }}</div>
html
<div>Loading...</div>
Vue 2 无原生 ``,需自行管理 loading 状态。
7. 全局 API 变更
js
// Vue 2
Vue.component('MyButton', MyButton)
Vue.directive('focus', focusDirective)
// Vue 3
import { createApp } from 'vue'
const app = createApp(App)
app.component('MyButton', MyButton)
app.directive('focus', focusDirective)
app.mount('#app')
Vue 3 的应用实例彼此隔离,适合微前端或多实例场景。
8. 生命周期钩子命名变化
js
// Vue 2
export default {
beforeDestroy() { /* cleanup */ },
destroyed() { /* final */ }
}
// Vue 3(Options API 写法)
export default {
beforeUnmount() { /* cleanup */ },
unmounted() { /* final */ }
}
// Vue 3(Composition API)
import { onBeforeUnmount, onUnmounted } from 'vue'
onBeforeUnmount(() => { /* cleanup */ })
onUnmounted(() => { /* final */ })
9. v-model 多绑定
html
10. 显式声明 emits(推荐)
js
const emit = defineEmits(['submit', 'cancel'])
const handleSubmit = () => emit('submit')
const emit = defineEmits({
submit: (payload) => typeof payload === 'string',
cancel: null
})
Vue 2 中 $emit 无需声明,但不利于工具链和文档生成。
这些示例覆盖了 Vue2 和 Vue3 比较关键的差异点。通过代码对比,可以更清楚地看到 Vue3 在开发体验、性能、灵活性和工程化方面有明细的提升。
结尾
总的来说,Vue3 在保持简单上手的同时,增加了更多实用又强大的功能。不管是写代码更轻松了,还是对 TypeScript、大型项目的支持更好了,都让开发者的工作变得更高效。
本文首发于公众号:程序员刘大华,专注分享前后端开发的实战笔记。关注我,少走弯路,一起进步!
📌往期精彩
《async/await 到底要不要加 try-catch?异步错误处理最佳实践》
《如何查看 SpringBoot 当前线程数?3 种方法亲测有效》