| 特性 | Vue2 | Vue3 |
|---|
| 响应式原理 | Object.defineProperty | Proxy |
| 组合式 API | 无(选项式 API) | 有(setup、ref、reactive 等) |
| 性能 | 较低 | 更高,支持 tree-shaking |
| TypeScript 支持 | 较弱 | 原生支持 TypeScript |
| Fragment | 不支持 | 支持 |
| Teleport | 无 | 支持 |
| Suspense | 无 | 支持 |
| 生命周期 | beforeCreate/created 等 | onBeforeMount/onMounted 等 |
| 全局 API | Vue.use/Vue.mixin 等 | app.use/app.mixin 等 |
| 自定义指令 | Vue.directive | app.directive |
| 事件总线 | this.$on/this.$emit | 推荐使用 mitt 等第三方库 |
| 指令 | 作用说明 |
|---|
| v-model | 双向数据绑定 |
| v-text | 绑定文本内容 |
| v-html | 绑定 HTML 内容 |
| v-if/v-else | 条件渲染 |
| v-show | 显隐切换 |
| v-bind(😃 | 动态绑定属性 |
| v-for | 列表渲染 |
| v-on(@) | 事件绑定 |
| is | 动态组件 |
<p :class="{ active: isActive, 'text-danger': hasError }"></p>
<p :style="obj"></p>
props: {
title: { type: [String, Number], default: '标题', required: true },
propF: { validator: value => ['success', 'warning', 'danger'].includes(value) }
}
- 局部组件:在
components 选项中注册 - 全局组件:
Vue.component("compA", CompA) (Vue2) 或 app.component("compA", CompA) (Vue3)
- 局部过滤器:在组件
filters 选项中定义 - 全局过滤器:Vue2 用
Vue.filter,Vue3 推荐用方法或 computed 替代
- Vue2:
Vue.directive("focus", {...}) - Vue3:
app.directive("focus", {...})
- mixins 可复用逻辑,组件方法优先级高于 mixin
- Vue3 推荐用组合式 API 替代 mixins
- 父子通信:props / $emit
- 跨级通信:provide/inject
- 兄弟通信:事件总线(Vue2),Vue3 推荐 mitt 或状态管理
- 全局状态:Vuex(Vue2),Pinia(Vue3)
- Vue2:Object.defineProperty,不能监听数组和对象新增属性
- Vue3:Proxy,支持所有数据类型的响应式
| Vue2 | Vue3 |
|---|
| beforeCreate | setup |
| created | setup |
| beforeMount | onBeforeMount |
| mounted | onMounted |
| beforeUpdate | onBeforeUpdate |
| updated | onUpdated |
| beforeDestroy | onBeforeUnmount |
| destroyed | onUnmounted |
const routes = [
{ path: '/', component: Home },
{ path: '/about', component: About }
];
const router = new VueRouter({ routes });
const router = createRouter({ history: createWebHistory(), routes });
- 推荐在
created(Vue2)或 setup/onMounted(Vue3)中请求数据
- Vue2 推荐 Vuex
- Vue3 推荐 Pinia(更轻量、类型友好)
v-once:只渲染一次v-pre:跳过编译v-cloak:防止闪烁v-slot:插槽语法(Vue2.6+,Vue3更简洁)
import { ref, reactive, computed, watch, onMounted } from 'vue';
export default {
setup() {
const count = ref(0);
const state = reactive({ msg: 'hello' });
const double = computed(() => count.value * 2);
watch(count, (newVal) => { console.log(newVal); });
onMounted(() => { console.log('mounted'); });
return { count, state, double };
}
}
更多内容可参阅官方文档。