From 026f4a5958719bda345188b8146e4c39e6701af1 Mon Sep 17 00:00:00 2001 From: dj <1042039504@qq.com> Date: Fri, 27 Feb 2026 21:00:53 +0800 Subject: [PATCH] =?UTF-8?q?feat(runtime):=20=E5=AE=9E=E7=8E=B0=E7=B1=BB?= =?UTF-8?q?=E5=90=8D=E8=A7=84=E8=8C=83=E5=8C=96=E5=8A=9F=E8=83=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 添加 normalizeClass 函数用于处理类名数组和对象 - 在 createVNode 中集成类名规范化逻辑 - 导出 normalizeClass 供外部使用 - 创建测试 HTML 示例验证类名功能 - 处理字符串、数组和对象类型的类名输入 --- packages/runtime-core/src/vnode.ts | 8 ++++++ packages/shared/src/index.ts | 1 + packages/shared/src/normalizeProp.ts | 24 ++++++++++++++++ .../vue/examples/runtime/h-element-class.html | 28 +++++++++++++++++++ 4 files changed, 61 insertions(+) create mode 100644 packages/shared/src/normalizeProp.ts create mode 100644 packages/vue/examples/runtime/h-element-class.html diff --git a/packages/runtime-core/src/vnode.ts b/packages/runtime-core/src/vnode.ts index 2acd86b..6710bb3 100644 --- a/packages/runtime-core/src/vnode.ts +++ b/packages/runtime-core/src/vnode.ts @@ -3,6 +3,7 @@ import { isFunction, isObject, isString, + normalizeClass, ShapeFlags } from '@vue/shared' @@ -21,6 +22,13 @@ export function isVNode(value): value is VNode { return value ? value.__v_isVNode === true : false } export function createVNode(type, props, children): VNode { + if (props) { + let { class: klass, style } = props + if (klass && !isString(klass)) { + props.class = normalizeClass(klass) + } + } + const shapeFlag = isString(type) ? ShapeFlags.ELEMENT : isObject(type) diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.ts index 84dee3c..dcd7b1e 100644 --- a/packages/shared/src/index.ts +++ b/packages/shared/src/index.ts @@ -1,4 +1,5 @@ export { ShapeFlags } from './shapeFlags' +export { normalizeClass } from './normalizeProp' //判断是否为一个数组 export const isArray = Array.isArray diff --git a/packages/shared/src/normalizeProp.ts b/packages/shared/src/normalizeProp.ts new file mode 100644 index 0000000..f212a1f --- /dev/null +++ b/packages/shared/src/normalizeProp.ts @@ -0,0 +1,24 @@ +import { isArray, isObject, isString } from '@vue/shared' + +export function normalizeClass(value: unknown): string { + let res = '' + + if (isString(value)) { + res = value + } else if (isArray(value)) { + for (let i = 0; i < value.length; i++) { + const normalized = normalizeClass(value[i]) + if (normalized) { + res += normalized + ' ' + } + } + } else if (isObject(value)) { + for (const name in value as object) { + if ((value as object)[name]) { + res += name + ' ' + } + } + } + + return res.trim() +} diff --git a/packages/vue/examples/runtime/h-element-class.html b/packages/vue/examples/runtime/h-element-class.html new file mode 100644 index 0000000..cecb349 --- /dev/null +++ b/packages/vue/examples/runtime/h-element-class.html @@ -0,0 +1,28 @@ + +
+ + +