From 6809dbeffa91fae3b454c8d7471499f5769bbf58 Mon Sep 17 00:00:00 2001 From: qiang Date: Tue, 18 May 2021 17:45:25 +0800 Subject: [PATCH] feat: initCostomDataset --- .../uni-core/src/view/plugin/costomDataset.ts | 40 +++++++++++++++++++ packages/uni-core/src/view/plugin/index.ts | 3 ++ 2 files changed, 43 insertions(+) create mode 100644 packages/uni-core/src/view/plugin/costomDataset.ts diff --git a/packages/uni-core/src/view/plugin/costomDataset.ts b/packages/uni-core/src/view/plugin/costomDataset.ts new file mode 100644 index 000000000..f7c50c421 --- /dev/null +++ b/packages/uni-core/src/view/plugin/costomDataset.ts @@ -0,0 +1,40 @@ +import { camelize } from '@vue/shared' +interface HTMLElementWithDataset extends HTMLElement { + __uniDataset?: Record +} + +function formatKey(key: string) { + return camelize(key.substring(5)) +} + +export function initCostomDataset() { + const prototype = HTMLElement.prototype + const setAttribute = prototype.setAttribute + prototype.setAttribute = function (key, value) { + if (key.startsWith('data-') && this.tagName.startsWith('UNI-')) { + const dataset = ((this as HTMLElementWithDataset).__uniDataset = + (this as HTMLElementWithDataset).__uniDataset || {}) + dataset[formatKey(key)] = value + } + setAttribute.call(this, key, value) + } + const removeAttribute = prototype.removeAttribute + prototype.removeAttribute = function (key) { + if ( + (this as HTMLElementWithDataset).__uniDataset && + key.startsWith('data-') && + this.tagName.startsWith('UNI-') + ) { + delete (this as HTMLElementWithDataset).__uniDataset![formatKey(key)] + } + removeAttribute.call(this, key) + } +} + +export function getCostomDataset(el: HTMLElement | HTMLElementWithDataset) { + return Object.assign( + {}, + el.dataset, + (el as HTMLElementWithDataset).__uniDataset + ) +} diff --git a/packages/uni-core/src/view/plugin/index.ts b/packages/uni-core/src/view/plugin/index.ts index e9108c997..7d9ce3c7f 100644 --- a/packages/uni-core/src/view/plugin/index.ts +++ b/packages/uni-core/src/view/plugin/index.ts @@ -2,11 +2,14 @@ import { App } from 'vue' import { initLongPress } from './longPress' import { initAppConfig } from './appConfig' +import { initCostomDataset } from './costomDataset' +export { getCostomDataset } from './costomDataset' export function initView(app: App) { if (__NODE_JS__) { return } + initCostomDataset() if (__UNI_FEATURE_LONGPRESS__) { initLongPress() } -- GitLab