From 2d9f1360778154a232473fcf93f6164a6bd80ca5 Mon Sep 17 00:00:00 2001 From: t-zzzzzzzzz Date: Wed, 6 May 2020 23:14:07 +0800 Subject: [PATCH] fix(runtime-dom/style): normalize string when merging styles (#1127) --- packages/runtime-core/__tests__/vnode.spec.ts | 28 +++++++++++++++++++ packages/shared/src/normalizeProp.ts | 15 +++++++++- 2 files changed, 42 insertions(+), 1 deletion(-) diff --git a/packages/runtime-core/__tests__/vnode.spec.ts b/packages/runtime-core/__tests__/vnode.spec.ts index e8bde9bcc83..341e840de73 100644 --- a/packages/runtime-core/__tests__/vnode.spec.ts +++ b/packages/runtime-core/__tests__/vnode.spec.ts @@ -258,6 +258,34 @@ describe('vnode', () => { } }) }) + test('style', () => { + let props1: Data = { + style: 'width:100px;right:10;top:10' + } + let props2: Data = { + style: [ + { + color: 'blue', + width: '200px' + }, + { + width: '300px', + height: '300px', + fontSize: 30 + } + ] + } + expect(mergeProps(props1, props2)).toMatchObject({ + style: { + color: 'blue', + width: '300px', + height: '300px', + fontSize: 30, + right: 10, + top: 10 + } + }) + }) test('handlers', () => { let clickHandler1 = function() {} diff --git a/packages/shared/src/normalizeProp.ts b/packages/shared/src/normalizeProp.ts index 77357c681a8..3546fa04b70 100644 --- a/packages/shared/src/normalizeProp.ts +++ b/packages/shared/src/normalizeProp.ts @@ -7,7 +7,8 @@ export function normalizeStyle( if (isArray(value)) { const res: Record = {} for (let i = 0; i < value.length; i++) { - const normalized = normalizeStyle(value[i]) + const styles = isString(value[i]) ? strStyleToObj(value[i]) : value[i] + const normalized = normalizeStyle(styles) if (normalized) { for (const key in normalized) { res[key] = normalized[key] @@ -20,6 +21,18 @@ export function normalizeStyle( } } +function strStyleToObj(style: string) { + const ret: Record = {} + style + .replace(/\s*/g, '') + .split(';') + .forEach((item: string) => { + const [key, val] = item.split(':') + ret[key] = isNaN(Number(val)) ? val : Number(val) + }) + return ret +} + export function stringifyStyle( styles: Record | undefined ): string {