,否则会报错。
...
...
Vue3,我们可以在组件中有多个根节点,这样我们就可以少写一层了,!
...
...
异步组件
Vue3 提供的组件允许程序在等待异步组件的同时渲染底线内容,例如让用户体验更流畅。 要使用它,请在模板中声明它并包含两个命名插槽:和。 确保在异步内容加载完成时显示默认插槽,并将插槽用作加载状态。
#default>
#fallback>
Loading...
在实际项目中,如果要在setup中调用异步请求,需要在setup前加上async关键字。 这时候,你会被警告async setup() is used a .
解决方法:在父页面外包裹一层组件调用当前组件。
Vue3 提供了组件来将部分 DOM 移动到 Vue 应用程序之外的位置。 比如项目中的常用组件。
"body">
"dialog" v-if="dialogVisible">
复合API
Vue2是一个可选的API(API),一个逻辑会分散在文件的不同位置(data、props、watch、 等),导致代码可读性差,需要上下跳转文件位置。 Vue3的组合API(API)很好的解决了这个问题,可以把相同逻辑的内容写到一起。
除了增强代码的可读性和内聚性之外,组合的API还提供了更完善的逻辑复用性解决方案。 例如,以下示例显示了常用的鼠标坐标。
// main.vue
mouse position {{x}} {{y}}
cript setup>
import { ref } from 'vue'
import useMousePosition from './useMousePosition'
const {x, y} = useMousePosition()
}
cript>
// useMousePosition.js
import { ref, onMounted, onUnmounted } from 'vue'
function useMousePosition() {
let x = ref(0)
let y = ref(0)
function update(e) {
x.value = e.pageX
y.value = e.pageY
}
onMounted(() => {
window.addEventListener('mousemove', update)
})
onUnmounted(() => {
window.removeEventListener('mousemove', update)
})
return {
x,
y
}
}
cript>
解决了Vue2 Mixin命名冲突,依赖关系不清晰,不同组件之间配置不够灵活的隐患。
反应原则
Vue2 响应式原则的基础是 .; Vue3响应式原理的基础是Proxy。
.
基本用法:直接在一个对象上定义新的属性或修改已有的属性,并返回该对象。
Tips:and值和and不要并存。
let obj = {}
let name = '瑾行'
Object.defineProperty(obj, 'name', {
enumerable: true, // 可枚举(是否可通过for...in 或 Object.keys()进行访问)
configurable: true, // 可配置(是否可使用delete删除,是否可再次设置属性)
// value: '', // 任意类型的值,默认undefined
// writable: true, // 可重写
get: function() {
return name
},
set: function(value) {
name = value
}
})
移植Vue2核心源码,略有删减。
function defineReactive(obj, key, val) {
// 一 key 一个 dep
const dep = new Dep()
// 获取 key 的属性描述符,发现它是不可配置对象的话直接 return
const property = Object.getOwnPropertyDescriptor(obj, key)
if (property && property.configurable === false) { return }
// 获取 getter 和 setter,并获取 val 值
const getter = property && property.get
const setter = property && property.set
if((!getter || setter) && arguments.length === 2) { val = obj[key] }
// 递归处理,保证对象中所有 key 被观察
let childOb = observe(val)
Object.defineProperty(obj, key, {
enumerable: true,
configurable: true,
// get 劫持 obj[key] 的 进行依赖收集
get: function reactiveGetter() {
const value = getter ? getter.call(obj) : val
if(Dep.target) {
// 依赖收集
dep.depend()
if(childOb) {
// 针对嵌套对象,依赖收集
childOb.dep.depend()
// 触发数组响应式
if(Array.isArray(value)) {
dependArray(value)
}
}
}
}
return value
})
// set 派发更新 obj[key]
set: function reactiveSetter(newVal) {
...
if(setter) {
setter.call(obj, newVal)
} else {
val = newVal
}
// 新值设置响应式
childOb = observe(val)
// 依赖通知更新
dep.notify()
}
}
那么为什么Vue3放弃了呢? 那一定有一些缺陷。
主要原因:无法监控对象或数组的新增和删除元素。
Vue2解决方案:对常见的数组原型方法push、pop、shift、、、sort进行hack处理,提供Vue.set监听对象/数组新属性。 响应于添加/删除对象,也可以创建新对象。 添加合并新属性和旧对象; 删除是指将删除属性后的对象深拷贝到新的对象中。
Tips:监听数组中已有的元素是可以的,但是Vue2之所以不提供是因为性能问题。 详情请参考第二篇~。
代理人
Proxy是ES6的新特性,通过第二个参数拦截目标对象的行为。 相比之下,提供了全方位的语言响应能力,消除了局限性。 但是在兼容性方面放弃了(IE11以下)
局限性
添加和删除对象/数组。
监视器。 调整。
支持映射、集合和。
基本用法:为对象创建代理,实现基本操作和自定义操作的拦截。
const handler = {
get: function(obj, prop) {
return prop in obj ? obj[prop] : ''
},
set: function() {},
...
}
移植Vue3的源码.ts文件
function createReactiveObject(target, isReadOnly, baseHandlers, collectionHandlers, proxyMap) {
...
// collectionHandlers: 处理Map、Set、WeakMap、WeakSet
// baseHandlers: 处理数组、对象
const proxy = new Proxy(
target,
targetType === TargetType.COLLECTION ? collectionHandlers : baseHandlers
)
proxyMap.set(target, proxy)
return proxy
}
以.ts为例,之所以使用.get而不是[key],是因为参数可以在调用时将this指向对象,而不是构造Proxy时的对象。
// 依赖收集
function createGetter(isReadonly = false, shallow = false) {
return function get(target: Target, key: string | symbol, receiver: object) {
...
// 数组类型
const targetIsArray = isArray(target)
if (!isReadonly && targetIsArray && hasOwn(arrayInstrumentations, key)) {
return Reflect.get(arrayInstrumentations, key, receiver)
}
// 非数组类型
const res = Reflect.get(target, key, receiver);
// 对象递归调用
if (isObject(res)) {
return isReadonly ? readonly(res) : reactive(res)
}
return res
}
}
// 派发更新
function createSetter() {
return function set(target: Target, key: string | symbol, value: unknown, receiver: Object) {
value = toRaw(value)
oldValue = target[key]
// 因 ref 数据在 set value 时就已 trigger 依赖了,所以直接赋值 return 即可
if (!isArray(target) && isRef(oldValue) && !isRef(value)) {
oldValue.value = value
return true
}
// 对象是否有 key 有 key set,无 key add
const hadKey = hasOwn(target, key)
const result = Reflect.set(target, key, value, receiver)
if (target === toRaw(receiver)) {
if (!hadKey) {
trigger(target, TriggerOpTypes.ADD, key, value)
} else if (hasChanged(value, oldValue)) {
trigger(target, TriggerOpTypes.SET, key, value, oldValue)
}
}
return result
}
}
虚拟DOM
与 Vue2 相比,Vue3 在虚拟 DOM 中增加了字段。 让我们借助 Vue3 来看一下。
"app">
技术摸鱼
今天天气真不错
{{name}}
渲染函数如下。
import { createElementVNode as _createElementVNode, toDisplayString as _toDisplayString, openBlock as _openBlock, createElementBlock as _createElementBlock, pushScopeId as _pushScopeId, popScopeId as _popScopeId } from "vue"
const _withScopeId = n => (_pushScopeId("scope-id"),n=n(),_popScopeId(),n)
const _hoisted_1 = { id: "app" }
const _hoisted_2 = _withScopeId(() => _createElementVNode("h1", null, "技术摸鱼", -1 ))
const _hoisted_3 = _withScopeId(() => _createElementVNode("p", null, "今天天气真不错", -1 ))
export function render(_ctx, _cache, $props, $setup, $data, $options) {
return (_openBlock(), _createElementBlock("div", _hoisted_1, [
_hoisted_2,
_hoisted_3,
_createElementVNode("div", null, _toDisplayString(_ctx.name), 1 )
]))
}
注意第三个的第四个参数是字段类型,字段类型如下。 1表示该节点是一个动态的文本节点,所以在diff过程中,只需要比较文本内容,不需要关注class,style等。另外发现都是静态的节点保存为静态提升的变量,重新渲染时可以直接引用,无需重新创建。
export const enum PatchFlags {
TEXT = 1, // 动态文本内容
CLASS = 1 << 1, // 动态类名
STYLE = 1 << 2, // 动态样式
PROPS = 1 << 3, // 动态属性,不包含类名和样式
FULL_PROPS = 1 << 4, // 具有动态 key 属性,当 key 改变,需要进行完整的 diff 比较
HYDRATE_EVENTS = 1 << 5, // 带有监听事件的节点
STABLE_FRAGMENT = 1 << 6, // 不会改变子节点顺序的 fragment
KEYED_FRAGMENT = 1 << 7, // 带有 key 属性的 fragment 或部分子节点
UNKEYED_FRAGMENT = 1 << 8, // 子节点没有 key 的fragment
NEED_PATCH = 1 << 9, // 只会进行非 props 的比较
DYNAMIC_SLOTS = 1 << 10, // 动态的插槽
HOISTED = -1, // 静态节点,diff阶段忽略其子节点
BAIL = -2 // 代表 diff 应该结束
}
事件缓存
Vue3 可以在第一次渲染后缓存我们的事件。 与Vue2相比,不需要每次渲染都传入一个新的函数。 添加点击事件。
"app">
技术摸鱼
今天天气真不错
{{name}}
nCLick="() => {}">
渲染函数如下
import { createElementVNode as _createElementVNode, toDisplayString as _toDisplayString, openBlock as _openBlock, createElementBlock as _createElementBlock, pushScopeId as _pushScopeId, popScopeId as _popScopeId } from "vue"
const _withScopeId = n => (_pushScopeId("scope-id"),n=n(),_popScopeId(),n)
const _hoisted_1 = { id: "app" }
const _hoisted_2 = _withScopeId(() => _createElementVNode("h1", null, "技术摸鱼", -1 ))
const _hoisted_3 = _withScopeId(() => _createElementVNode("p", null, "今天天气真不错", -1 ))
const _hoisted_4 = _withScopeId(() => _createElementVNode("span", { onCLick: "() => {}" }, [
_createElementVNode("span")
], -1 ))
export function render(_ctx, _cache, $props, $setup, $data, $options) {
return (_openBlock(), _createElementBlock("div", _hoisted_1, [
_hoisted_2,
_hoisted_3,
_createElementVNode("div", null, _toDisplayString(_ctx.name), 1 ),
_hoisted_4
]))
}
差异优化
移植 Vue3 源代码。 结合上面和源码,有助于在时区分静态节点和不同类型的动态节点。 在一定程度上减少节点本身及其属性的比较。
function patchChildren(n1, n2, container, parentAnchor, parentComponent, parentSuspense, isSVG, optimized) {
// 获取新老孩子节点
const c1 = n1 && n1.children
const c2 = n2.children
const prevShapeFlag = n1 ? n1.shapeFlag : 0
const { patchFlag, shapeFlag } = n2
// 处理 patchFlag 大于 0
if(patchFlag > 0) {
if(patchFlag && PatchFlags.KEYED_FRAGMENT) {
// 存在 key
patchKeyedChildren()
return
} els if(patchFlag && PatchFlags.UNKEYED_FRAGMENT) {
// 不存在 key
patchUnkeyedChildren()
return
}
}
// 匹配是文本节点(静态):移除老节点,设置文本节点
if(shapeFlag && ShapeFlags.TEXT_CHILDREN) {
if (prevShapeFlag & ShapeFlags.ARRAY_CHILDREN) {
unmountChildren(c1 as VNode[], parentComponent, parentSuspense)
}
if (c2 !== c1) {
hostSetElementText(container, c2 as string)
}
} else {
// 匹配新老 Vnode 是数组,则全量比较;否则移除当前所有的节点
if (prevShapeFlag & ShapeFlags.ARRAY_CHILDREN) {
if (shapeFlag & ShapeFlags.ARRAY_CHILDREN) {
patchKeyedChildren(c1, c2, container, anchor, parentComponent, parentSuspense,...)
} else {
unmountChildren(c1 as VNode[], parentComponent, parentSuspense, true)
}
} else {
if(prevShapeFlag & ShapeFlags.TEXT_CHILDREN) {
hostSetElementText(container, '')
}
if (shapeFlag & ShapeFlags.ARRAY_CHILDREN) {
mountChildren(c2 as VNodeArrayChildren, container,anchor,parentComponent,...)
}
}
}
}
源代码如下。
function patchUnkeyedChildren(c1, c2, container, parentAnchor, parentComponent, parentSuspense, isSVG, optimized) {
c1 = c1 || EMPTY_ARR
c2 = c2 || EMPTY_ARR
const oldLength = c1.length
const newLength = c2.length
const commonLength = Math.min(oldLength, newLength)
let i
for(i = 0; i < commonLength; i++) {
// 如果新 Vnode 已经挂载,则直接 clone 一份,否则新建一个节点
const nextChild = (c2[i] = optimized ? cloneIfMounted(c2[i] as Vnode)) : normalizeVnode(c2[i])
patch()
}
if(oldLength > newLength) {
// 移除多余的节点
unmountedChildren()
} else {
// 创建新的节点
mountChildren()
}
}
源码如下,采用最长递增序列的算法思想。
function patchKeyedChildren(c1, c2, container, parentAnchor, parentComponent, parentSuspense, isSVG, optimized) {
let i = 0;
const e1 = c1.length - 1
const e2 = c2.length - 1
const l2 = c2.length
// 从头开始遍历,若新老节点是同一节点,执行 patch 更新差异;否则,跳出循环
while(i <= e1 && i <= e2) {
const n1 = c1[i]
const n2 = c2[i]
if(isSameVnodeType) {
patch(n1, n2, container, parentAnchor, parentComponent, parentSuspense, isSvg, optimized)
} else {
break
}
i++
}
// 从尾开始遍历,若新老节点是同一节点,执行 patch 更新差异;否则,跳出循环
while(i <= e1 && i <= e2) {
const n1 = c1[e1]
const n2 = c2[e2]
if(isSameVnodeType) {
patch(n1, n2, container, parentAnchor, parentComponent, parentSuspense, isSvg, optimized)
} else {
break
}
e1--
e2--
}
// 仅存在需要新增的节点
if(i > e1) {
if(i <= e2) {
const nextPos = e2 + 1
const anchor = nextPos < l2 ? c2[nextPos] : parentAnchor
while(i <= e2) {
patch(null, c2[i], container, parentAnchor, parentComponent, parentSuspense, isSvg, optimized)
}
}
}
// 仅存在需要删除的节点
else if(i > e2) {
while(i <= e1) {
unmount(c1[i], parentComponent, parentSuspense, true)
}
}
// 新旧节点均未遍历完
// [i ... e1 + 1]: a b [c d e] f g
// [i ... e2 + 1]: a b [e d c h] f g
// i = 2, e1 = 4, e2 = 5
else {
const s1 = i
const s2 = i
// 缓存新 Vnode 剩余节点 上例即{e: 2, d: 3, c: 4, h: 5}
const keyToNewIndexMap = new Map()
for (i = s2; i <= e2; i++) {
const nextChild = (c2[i] = optimized
? cloneIfMounted(c2[i] as VNode)
: normalizeVNode(c2[i]))
if (nextChild.key != null) {
if (__DEV__ && keyToNewIndexMap.has(nextChild.key)) {
warn(
`Duplicate keys found during update:`,
JSON.stringify(nextChild.key),
`Make sure keys are unique.`
)
}
keyToNewIndexMap.set(nextChild.key, i)
}
}
}
let j = 0
// 记录即将 patch 的 新 Vnode 数量
let patched = 0
// 新 Vnode 剩余节点长度
const toBePatched = e2 - s2 + 1
// 是否移动标识
let moved = false
let maxNewindexSoFar = 0
// 初始化 新老节点的对应关系(用于后续最大递增序列算法)
const newIndexToOldIndexMap = new Array(toBePatched)
for (i = 0; i < toBePatched; i++) newIndexToOldIndexMap[i] = 0
// 遍历老 Vnode 剩余节点
for (i = s1; i <= e1; i++) {
const prevChild = c1[i]
// 代表当前新 Vnode 都已patch,剩余旧 Vnode 移除即可
if (patched >= toBePatched) {
unmount(prevChild, parentComponent, parentSuspense, true)
continue
}
let newIndex
// 旧 Vnode 存在 key,则从 keyToNewIndexMap 获取
if (prevChild.key != null) {
newIndex = keyToNewIndexMap.get(prevChild.key)
// 旧 Vnode 不存在 key,则遍历新 Vnode 获取
} else {
for (j = s2; j <= e2; j++) {
if (newIndexToOldIndexMap[j - s2] === 0 && isSameVNodeType(prevChild, c2[j] as VNode)){
newIndex = j
break
}
}
}
// 删除、更新节点
// 新 Vnode 没有 当前节点,移除
if (newIndex === undefined) {
unmount(prevChild, parentComponent, parentSuspense, true)
} else {
// 旧 Vnode 的下标位置 + 1,存储到对应 新 Vnode 的 Map 中
// + 1 处理是为了防止数组首位下标是 0 的情况,因为这里的 0 代表需创建新节点
newIndexToOldIndexMap[newIndex - s2] = i + 1
// 若不是连续递增,则代表需要移动
if (newIndex >= maxNewIndexSoFar) {
maxNewIndexSoFar = newIndex
} else {
moved = true
}
patch(prevChild,c2[newIndex],...)
patched++
}
}
// 遍历结束,newIndexToOldIndexMap = {0:5, 1:4, 2:3, 3:0}
// 新建、移动节点
const increasingNewIndexSequence = moved
// 获取最长递增序列
? getSequence(newIndexToOldIndexMap)
: EMPTY_ARR
j = increasingNewIndexSequence.length - 1
for (i = toBePatched - 1; i >= 0; i--) {
const nextIndex = s2 + i
const nextChild = c2[nextIndex] as VNode
const anchor = extIndex + 1 < l2 ? (c2[nextIndex + 1] as VNode).el : parentAnchor
// 0 新建 Vnode
if (newIndexToOldIndexMap[i] === 0) {
patch(null,nextChild,...)
} else if (moved) {
// 移动节点
if (j < 0 || i !== increasingNewIndexSequence[j]) {
move(nextChild, container, anchor, MoveType.REORDER)
} else {
j--
}
}
}
}
包装优化
tree-:模块打包等概念。去除上下文中没有引用的代码。 主要依赖and语句,用于检测代码模块是否被文件导出、导入、使用。
举个例子,在Vue2中,全局API是暴露在Vue实例上的,即使不用,也无法通过tree-消除。
import Vue from 'vue'
Vue.nextTick(() => {
// 一些和DOM有关的东西
})
在 Vue3 中,重构了全局和内部 API,同时考虑到了对 tree- 的支持。 因此,全局 API 现在只能作为 ES 模块构建的命名导出来访问。
import { nextTick } from 'vue'
nextTick(() => {
// 一些和DOM有关的东西
})
通过此更改,只要模块绑定器支持树,Vue 应用程序中未使用的 API 将从最终包中删除,从而获得最佳文件大小。 受此更改影响的全局 API 如下。
内部 API 也有按名称导出的标签或指令,例如 、v-model 等。 只有当程序真正被使用时,才会对其进行捆绑和打包。
根据友达直播了解到,现在Vue3将所有的运行函数都打包成一个只有22.5kb的包,比Vue2轻很多。
自定义渲染 API
Vue3默认提供的是映射到html。 但是如果要生成,需要使用api自定义生成函数。
// 自定义runtime-render函数
import { createApp } from './runtime-render'
import App from './src/App'
createApp(App).mount('#app')
支持
Vue3 由 TS 重写,比 Vue2 支持更好。
大约
列举一些Vue3的配套产品。 具体的API新语法可以在官方迁移文档中找到,参考中有链接~。
参考
Vue3.0性能优化改写虚拟Dom[1]
记一个思想问答题:为什么Vue不能检测数组变化[2]
Vue3源码解析系列——响应式原理(下)[3]
Vue源码解读(三)——响应式原理[4]
Vue 3 Dom Diff源码阅读[5]
Vue 2 迁移[6]
关于这篇文章