mipengine / mip2

MIP (移动网页加速器)通过优化网页JS、控制资源加载顺序,达到加速网页的效果。
https://www.mipengine.org/
MIT License
184 stars 49 forks source link

CustomElement 增强方案 #485

Closed yenshih closed 5 years ago

yenshih commented 5 years ago

要解决什么问题

发现写组件时总需要写好多重复代码

属性读取或暂存

const foo = this.element.getAttribute('foo')
const bar = this.element.getAttribute('bar')
this.foo = this.element.getAttribute('foo')
this.bar = this.element.getAttribute('bar')

属性类型转换

this.num = +this.element.getAttribute('num')
this.obj = jsonParse(this.element.getAttribute('obj'))

属性默认值

this.foo = DEFAULT_VALUE
if (this.element.hasAttribute('foo')) {
  this.foo = this.element.getAttribute('foo')
}

属性校验

this.status = this.element.getAttribute('status')
if (!['success', 'failure'].includes(this.status)) {
  // ...
}

属性废弃的话似乎不太好配置,暂时不写上来

希望能消灭这些组件模板代码,同时贴近现代主流框架,提供更好的开发体验

描述一下你理想中的解决方案

class MipExample extends CustomElement {
  static props = {
    fooBar: {
      type: String,
      default: 'baz'
    },
    num: {
      type: Number,
      required: true
    },
    obj: {
      type: Object,
      default: () => ({message: 'hello'})
    },
    status: {
      type: String,
      validator: (value) => ['success', 'failure'].includes(value)
    }
  }

  buildCallback () {
    const {fooBar, num, obj, status} = this.props

    this.element.innerHTML = `<div class="${status}">${obj.message} ${fooBar}</div>`.repeat(num)
  }
}
<mip-example foo-bar="world" num="8" status="success"></mip-example>

可以解决上述所有问题

描述你的备选方案

补充信息

huanghuiquan commented 5 years ago
  1. 支持 json 和 attribute 数据合并,json 优先级要比 attribute 高,attribute 自动转成驼峰

    <mip-example foo-bar="world" num="8" status="success">
    <script type="application/json">
    {
      "fooBar": "world" 
    }
    </script>
    </mip-example>

    如果 attribute 优先级比 json 高会导致 attitude 一些默认的属性如title 覆盖json的title的问题

  2. event 和 action 声明~ 具体怎么实现还没想好~