引入异步组件变更
vue2
// 不带选项的异步组件
const asyncPage = () => import('./NextPage.vue')
const asyncPage = {
component: () => import('./NextPage.vue'),
delay: 200,
timeout: 3000,
error: ErrorComponent,
loading: LoadingComponent
}
vue3
import { defineAsyncComponent } from 'vue'
// 不带选项的异步组件
const asyncPage = defineAsyncComponent(() => import('./NextPage.vue')) // defineAsyncComponent包裹
const asyncPageWithOptions = defineAsyncComponent({
loader: () => import('./NextPage.vue'), // component变更为loader
delay: 200,
timeout: 3000,
errorComponent: ErrorComponent,
loadingComponent: LoadingComponent
})
自定义指令 钩子变为生命周期
在 Vue 2,自定义指令是通过使用下面列出的钩子来创建的,这些钩子都是可选的
- bind - 指令绑定到元素后发生。只发生一次。
- inserted - 元素插入父 DOM 后发生。
- update - 当元素更新,但子元素尚未更新时,将调用此钩子。
- componentUpdated - 一旦组件和子级被更新,就会调用这个钩子。
- unbind - 一旦指令被移除,就会调用这个钩子。也只调用一次。
然而,在 Vue 3 中,我们为自定义指令创建了一个更具凝聚力的 API。正如你所看到的,它们与我们的组件生命周期方法有很大的不同,即使我们正与类似的事件钩子,我们现在把它们统一起来了:
- bind → beforeMount
- inserted → mounted
- beforeUpdate:新的!这是在元素本身更新之前调用的,很像组件生命周期钩子。
- update → 移除!有太多的相似之处要更新,所以这是多余的,请改用
updated。 - componentUpdated → updated
- beforeUnmount:新的!与组件生命周期钩子类似,它将在卸载元素之前调用。
- unbind -> unmounted
vue2
Vue.directive('highlight', {
bind(el, binding, vnode) {
el.style.background = binding.value
}
})
vue3
const app = Vue.createApp({}) // 使用方式变更
app.directive('highlight', {
beforeMount(el, binding, vnode) {
el.style.background = binding.value
}
})
Mixin 合并行为变更
当来自组件的 data() 及其 mixin 或 extends 基类被合并时,现在将浅层次执行合并:
const Mixin = {
data() {
return {
user: {
name: 'Jack',
id: 1
}
}
}
}
const CompA = {
mixins: [Mixin],
data() {
return {
user: {
id: 2
}
}
}
}
在 Vue 2中,生成的** data** 是:
{
user: {
id: 2,
name: 'Jack'
}
}
在 vue3 中,生成的 data 是:
{
user: {
id: 2
}
}
vue3废弃
$on,$off 和 $once 实例方法已被移除
过滤器已删除,不再支持。
全局api变更
vue2 组件
Vue.component('button-counter', {
data: () => ({
count: 0
}),
template: '<button @click="count++">Clicked {{ count }} times.</button>'
})
vue2 指令
Vue.directive('focus', {
inserted: el => el.focus()
})
vue3
import { createApp } from 'vue'
import MyApp from './MyApp.vue'
const app = createApp(MyApp)
app.component('button-counter', {
data: () => ({
count: 0
}),
template: '<button @click="count++">Clicked {{ count }} times.</button>'
})
app.directive('focus', {
mounted: el => el.focus()
})
// 现在所有应用实例都挂载了,与其组件树一起,将具有相同的 “button-counter” 组件 和 “focus” 指令不污染全局环境
app.mount('#app')
nextTick引用方式变更
vue2
import Vue from 'vue'
Vue.nextTick(() => {
// 一些和DOM有关的东西
})
vue3
import { nextTick } from 'vue'
nextTick(() => {
// 一些和DOM有关的东西
})
vue3 可以在template设置key
<template v-for="item in list" :key="item.id">
<div v-if="item.isVisible">...</div>
<span v-else>...</span>
</template>
vue3现在建议对任何要用作修饰符的键使用 kebab-cased (短横线) 大小写名称
<!-- Vue 3 在 v-on 上使用 按键修饰符 -->
<input v-on:keyup.delete="confirmDelete" />