区别
1、生命周期区别
Vue 3 生命周期基本兼容 Vue 2。但有命名变化。
| Vue 2 | Vue 3 |
|---|---|
| beforeCreate | setup() |
| created | setup() |
| beforeMount | beforeMount |
| mounted | mounted |
| beforeUpdate | beforeUpdate |
| updated | updated |
| beforeDestroy | beforeUnmount |
| destroyed | unmounted |
2、模板语法区别
绝大多数兼容。Vue 3 支持 Fragment:
<template>
<header></header>
<main></main>
</template>
Vue 2:组件只能一个根节点,如❌
<template>
<div></div>
<div></div>
</template>
3、watch
4、状态管理区别
Vue 2通常:
Vuex
Vue 3推荐:
Pinia
跟简单:
export const useStore = defineStore(
'counter',
() => {
const count = ref(0);
const add = () => count.value++;
return { count, add };
}
);
5、构建工具区别
二、VUE3新特性
1、Teleport(Vue 3 新增)
组件渲染到指定 DOM。
<teleport to="body">
<Modal />
</teleport>