今天在用elementUI 的时候,table的头部是有颜色小格子的,那么就需要去自定义table的头部,table组件提供了render-header
函数,颜色格子一定要用到标签,发现直接return 出去带有标签的字符串是解析不了的,搜了下,发现需要用到createElement
<el-table>
表头内插入 HTML 标签?跟着这个issues尝试了createElement
的使用,
第一个参数为一个 HTML 标签字符串,组件选项对象,后面两个参数为数据或者对象,两个顺序可以随意,
如果是一个HTML标签的话,
{
attrs:{
class:"beauty",
style:""
}
}
参数为字符串的话会将后面的{}设置覆盖掉,字符串就是innerText属性。
domProps: {
innerHTML: 'dddd'
},
最后一个参数为数组,里面存放的就是子组件
jsx的优势:
今天看了elementUI的pagination组件发现里面的事件写法很奇怪,on-click={ this.$parent.prev }>
是这么写的,在react中是驼峰命名法,于是查阅vue古方文档里面的render函数章节,发现里面并没有on-click
这种写法,还有一点比较奇怪,render函数没有返回vnode组件(就是没有使用createElement
),而是直接返回了HTML字符串。
pagination.js
render(h) {
let template = <div class='el-pagination'></div>;
const layout = this.layout || '';
if (!layout) return;
const TEMPLATE_MAP = {
prev: <prev></prev>,
jumper: <jumper></jumper>,
pager: <pager currentPage={ this.internalCurrentPage } pageCount={ this.internalPageCount } on-change={ this.handleCurrentChange }></pager>,
next: <next></next>,
sizes: <sizes pageSizes={ this.pageSizes }></sizes>,
slot: <my-slot></my-slot>,
total: <total></total>
};
const components = layout.split(',').map((item) => item.trim());
const rightWrapper = <div class="el-pagination__rightwrapper"></div>;
let haveRightWrapper = false;
if (this.small) {
template.data.class += ' el-pagination--small';
}
components.forEach(compo => {
if (compo === '->') {
haveRightWrapper = true;
return;
}
if (!haveRightWrapper) {
template.children.push(TEMPLATE_MAP[compo]);
} else {
rightWrapper.children.push(TEMPLATE_MAP[compo]);
}
});
if (haveRightWrapper) {
template.children.push(rightWrapper);
}
return template;
},
里面的子组件也是直接返回HTML字符串的
原来这是jsx的语法,使用了babel-plugin-transform-vue-jsx去支持jsx语法,在这个库中看到
render (h) {
return (
<div
// normal attributes or component props.
id="foo"
// DOM properties are prefixed with `domProps`
domPropsInnerHTML="bar"
// event listeners are prefixed with `on` or `nativeOn`
onClick={this.clickHandler}
nativeOnClick={this.nativeClickHandler}
// other special top-level properties
class={{ foo: true, bar: false }}
style={{ color: 'red', fontSize: '14px' }}
key="key"
ref="ref"
// assign the `ref` is used on elements/components with v-for
refInFor
slot="slot">
</div>
)
}
他事件绑定的方式是用驼峰命名的onClick
我现在用的element的版本是1.2.8,查看了最新的1.4依旧用的on-click
方式Vue jsx 和 React jsx 的一些不同点这篇文章说vue2.1开始支持驼峰的。
jsx语法的优势:
- 不用每次都createElement 返回vnode,直接使用正常的HTML嵌套的格式,组件嵌套也是如此,
import AnchoredHeading from './AnchoredHeading.vue'
new Vue({
el: '#demo',
render (h) {
return (
<AnchoredHeading level={1}>
<span>Hello</span> world!
</AnchoredHeading>
)
}
})
- 事件属性直接写在标签上,不用在配置参数里配置各个属性和事件,上面就是直接写的。
createElement 的属性和事件配置:
on: {
click: this.clickHandler
},
// 正常的 HTML 特性
attrs: {
id: 'foo'
},
// 组件 props
props: {
myProp: 'bar'
},
element-ui 中哪些使用了jsx语法:
vue : pagination tabs dropdown scrollbar upload
js: col row tooltip