feat(runtime): 实现类名规范化功能
- 添加 normalizeClass 函数用于处理类名数组和对象 - 在 createVNode 中集成类名规范化逻辑 - 导出 normalizeClass 供外部使用 - 创建测试 HTML 示例验证类名功能 - 处理字符串、数组和对象类型的类名输入
This commit is contained in:
@@ -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)
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
export { ShapeFlags } from './shapeFlags'
|
||||
export { normalizeClass } from './normalizeProp'
|
||||
//判断是否为一个数组
|
||||
export const isArray = Array.isArray
|
||||
|
||||
|
||||
24
packages/shared/src/normalizeProp.ts
Normal file
24
packages/shared/src/normalizeProp.ts
Normal file
@@ -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()
|
||||
}
|
||||
28
packages/vue/examples/runtime/h-element-class.html
Normal file
28
packages/vue/examples/runtime/h-element-class.html
Normal file
@@ -0,0 +1,28 @@
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>Document</title>
|
||||
<script src="../../dist/vue.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
</body>
|
||||
<script>
|
||||
const {h} =Vue
|
||||
const vnode=h('div',{
|
||||
class:[
|
||||
{
|
||||
'red':true,
|
||||
},
|
||||
{
|
||||
'pink':true,
|
||||
},
|
||||
{
|
||||
'blue':false
|
||||
}
|
||||
]
|
||||
},'增强class')
|
||||
console.log(vnode)
|
||||
</script>
|
||||
</html>
|
||||
Reference in New Issue
Block a user