Render函数封装一个可排序的表格组件

主要思路:

      在v-table组件props接受两个参数,一个就是有多少列columns(数组),另一个就是data(数组),同时又简单的添加一个stripe是否给表格设置一个简单的样式.如下图:

接下来就是render主要思想:在构造元素时,首先要构造标题(<th>),那么就要循环父组件传来的columns数组,不断的遍历里面的对象循环显示(但是在有排序功能的需要再添加a标签),同理:循环显示data,不说了,直接上代码:

render:function(h){//在这里构造DOM

var _this = this;

//构造表格的头部标题

var ths = [];

this.currentColumns.forEach((col,index) => {

if(col.sortTable){

ths.push(h('th',[

h('span',col.title),

h('a',{

class:{//这是设置点击后的css属性 ,逻辑就是当我点击了会在函数中修改_sortType的值,在这里根据值去设定属性

on:col._sortType === 'asc'

},

on:{

click:function(){

_this.handleSortByAsc(index);//点击处理排序函数

}

}

},'↑'),

h('a',{

class:{

on:col._sortType === 'desc'

},

on:{

click:function(){

_this.handleSortByDesc(index);

}

}

},'↓')

]))

}else{

ths.push(h('th',col.title));

}

});

//构造表格的内容

var trs = [];

this.currentData.forEach((row,index) => {

var tds = [];

_this.currentColumns.forEach((cell) => {

tds.push(h('td',row[cell.key]));

});

if(index%2 != 0){//此处就是为了实现stricpe的表格样式

trs.push(h('tr',{

class:{

trStyle:_this.stripe

}

},tds));

}else{

trs.push(h('tr',tds));

}

});

//返回整体的表格系统

return h('table',[

h('thead',[

h('tr',ths)

]),

h('tbody',trs)

])

},

主要的思想已经表明  全部代码和解释,上传到gtihub:https://github.com/yanggreater/vue-personal-components/tree/master/render%E5%88%9B%E5%BB%BA%E8%A1%A8%E6%A0%BC%E7%BB%84%E4%BB%B6

猜你喜欢

转载自blog.csdn.net/yanggreater/article/details/81744177