给uniapp uni-table表格组件添加class和style

1,175 阅读2分钟

uniapp官方提供的扩展组件中,table在H5和小程序渲染逻辑是不一样的。h5 可直接在uni-th和uni-td 中填写style 或者class名称并正常工作。小程序则直接渲染view,忽略掉传递的class和style参数。

代码如下图所示:

H5如下图所示:

小程序如下图所示:

不知道为什么官方没有提供参数传递过去。为了解决这个问题,只能直接修改源码来实现了:

一般uniapp的扩展库都会放在src/uni_modules 目录,在这个目录找到uni-table库,这个目录就是table的库文件所在。我们只需要修改2个库文件。相对地址如下:

  1. 您的uniapp项目\src\uni_modules\uni-table\components\uni-th\uni-th.vue
  2. 您的uniapp项目\src\uni_modules\uni-table\components\uni-td\uni-td.vue

我们直接拿其中一个文件修改来说明(uni-td.vue):

修改template部分代码:

<template>    
<!-- #ifdef H5 -->    
<td class="uni-table-td" :rowspan="rowspan" :colspan="colspan" :class="[customClass, { 'table--border': border }]"        :style="[customStyle, { width: width + 'px', 'text-align': align }]">        
<slot></slot>    
</td>    
<!-- #endif -->
    
<!-- #ifndef H5 -->    
<!-- :class="{'table--border':border}"  -->    
<view class="uni-table-td" :class="[customClass, { 'table--border': border }]"        :style="[customStyle, { width: width + 'px', 'text-align': align }]">        
<slot></slot>   
 </view>    
<!-- #endif -->
</template>

差异如下图所示:

修改逻辑说明:

我们在table库中的:class 和 :style 分别引入customClass和customStyle 。即修改上述代码中对应的部分::class="[customClass, { 'table--border': border }]" 和 :style="[customStyle, { width: width + 'px', 'text-align': align }]"。记住H5和小程序都要修改,不然两端都不会起效的。

接着添加传递参数逻辑,在script部分找到props 对象区域,添加customClass和customStyle 。

props 对象区域:

	props: {
		width: {
			type: [String, Number],
			default: ''
		},
		align: {
			type: String,
			default: 'left'
		},
		rowspan: {
			type: [Number, String],
			default: 1
		},
		colspan: {
			type: [Number, String],
			default: 1
		},
		customClass: {
			type: String,
			default: ''
		},
		customStyle: {
			type: String,
			default: ''
		}
	},

至此,table库已经支持传递class和style样式了。我们会带修改业务代码。如下图所示:

最后看效果,小程序view 部分正确渲染我们自定义的style样式了。