leafer-ui icon indicating copy to clipboard operation
leafer-ui copied to clipboard

让业务数据data.xx控制元素的样式.最佳实践应该怎么做?

Open Gorvey opened this issue 4 months ago • 1 comments

比如data.type 为1的时候需要边框为蓝色,2需要边框为红色

new Rect({
  data:{
    type:1
  }
})

目前我的做法是在上层框架vue中,重写官网文档提供的proxyData示例,使用watch深度监听data对象的变化,然后调用函数updateMarkStyleAndReselect更新样式

还有更好的方式吗?

// 创建响应式数据

UI.prototype.createProxyData = function () {
  // 1.获取所有样式数据(含默认值)
  const data = this.__.__getData()

  // 2. 生成响应式数据
  const proxyData = shallowReactive(data)

  // 对 data 字段单独进行深度响应式处理
  if (data.data && typeof data.data === 'object') {
    proxyData.data = reactive(data.data)
  }

  // 3.观察响应式数据变化,同步更新元素数据
  for (const name in data) {
    if (name === 'data') {
      // 对 data 字段进行深度监听
      watch(
        () => proxyData[name], // source
        (newValue: IMark) => {
          updateMarkStyleAndReselect(this as RectWithData)
          if (this.__.__get(name) !== newValue) (this as any)[name] = newValue
        },
        { deep: true, immediate: true } // 仅对 data 字段深度监听
      )
    } else if (shallowReactiveList.includes(name)) {
      // 只监听特定字段列表中的字段
      watch(
        () => proxyData[name], // source
        newValue => {
          // console.log('只监听特定字段列表中的字段', name)
          if (this.__.__get(name) !== newValue) (this as any)[name] = newValue
        }
      )
    } else {
      // 其他字段不进行监听
    }
  }

  return proxyData
}

Gorvey avatar Sep 09 '25 03:09 Gorvey

目前这就是比较高效的方法了。

或者可以换一个思路,用state实现切换状态, 预定义好states列表,文档可以搜索一下states。

leaferjs avatar Sep 09 '25 06:09 leaferjs