diff --git a/__tests__/model/cell.spec.ts b/__tests__/model/cell.spec.ts index f39d2025217..3527308ba9a 100644 --- a/__tests__/model/cell.spec.ts +++ b/__tests__/model/cell.spec.ts @@ -125,6 +125,18 @@ describe('Cell core API', () => { expect(c.isVisible()).toBe(true) }) + it('data API: getData options reference', () => { + const c = new Cell({ data: { n: 1 } }) + + expect(c.getData()).toEqual({ n: 1 }) + + expect(c.getData()).toBe(c.getData()) + expect(c.getData({ reference: true })).toBe(c.getData()) + + expect(c.getData({ reference: false })).toEqual(c.getData()) + expect(c.getData({ reference: false })).not.toBe(c.getData()) + }) + it('data API: setData, replaceData, updateData, removeData', () => { const c = new Cell({ data: { n: 1 } }) expect(c.getData()).toEqual({ n: 1 }) diff --git a/site/docs/api/model/cell.en.md b/site/docs/api/model/cell.en.md index d7af37c6ff3..7c34d9e2e3a 100644 --- a/site/docs/api/model/cell.en.md +++ b/site/docs/api/model/cell.en.md @@ -1321,11 +1321,16 @@ Set the associated data and trigger the `change:data` event and canvas redraw. #### getData() ```ts -getData(): any +getData(options?: Cell.GetDataOptions): any ``` Get the associated data. +By default, it returns a reference to the original object. + +| Name | Type | Required | Default | Description | +|-------------------|---------|:----:|---------|----------------------------------------------------------------------------------------| +| options.reference | boolean | | `true` | When `true`, it returns a reference to the original object, otherwise returns a deep copy. | #### setData(...) ```ts diff --git a/site/docs/api/model/cell.zh.md b/site/docs/api/model/cell.zh.md index f0f98957a9f..9fc460e75b2 100644 --- a/site/docs/api/model/cell.zh.md +++ b/site/docs/api/model/cell.zh.md @@ -1321,11 +1321,17 @@ const rect = new Shape.Rect({ #### getData() ```ts -getData(): any +getData(options?: Cell.GetDataOptions): any ``` 获取关联的数据。 +默认返回原始对象的引用 + +| 名称 | 类型 | 必选 | 默认值 | 描述 | +|-------------------|---------|:----:|---------|----------------------------------------------------------------------------------------| +| options.reference | boolean | | `true` | 为 `true` 时返回原始对象的引用,否则返回其深拷贝。 | + #### setData(...) ```ts diff --git a/src/model/cell.ts b/src/model/cell.ts index 2dd220b6949..2e1bdc6e6b4 100644 --- a/src/model/cell.ts +++ b/src/model/cell.ts @@ -706,8 +706,13 @@ export class Cell< this.setData(val) } - getData(): T { - return this.store.get('data') + getData(options: Cell.GetDataOptions = {}): T { + const result = this.store.get('data') + + if (options.reference === false) { + return ObjectExt.cloneDeep(result) + } + return result } setData(data: T, options: Cell.SetDataOptions = {}) { @@ -1569,6 +1574,10 @@ export namespace Cell { deep?: boolean keepId?: boolean } + + export interface GetDataOptions { + reference?: boolean + } } export namespace Cell {