vue element-ui table组件的动态label和动态slot跳转

近期工作中有个需求需要对多条每个月数据进行表格展示,由于每个月数据是递增的今年5月、6月、7月等,并且用户能够根据点击的月份数据跳转到当月详情。

用户名 userid 2021-09 2021-10 2021-11 2021-12 你是帅哥 123 12 13 14 看你确实有点帅 123 24 25 26 30

接受数据例子:

json = {
          
   
	content:[
				{
          
   
				userName:‘你是帅哥’,
				userId: ‘123’
				monthData: [
					{
          
   key:2021-09,value:12},
					{
          
   key:2021-10,value:13},
					{
          
   key:2021-11,value:14}
					]
				},
				{
          
   
				userName:‘看你确实有点帅’,
				userId: ‘12345’
					monthData: [
					{
          
   key:2021-09,value:24},
					{
          
   key:2021-10,value:25},
					{
          
   key:2021-11,value:26},
					{
          
   key:2021-12,value:30}
					]
				}
			]
		}
  1. 由于需要将monthData数据按月份加入到表格label中 所以table组件的label不能直接写死,需要随着数据增加而动态增加。
  2. 对于表格中每月的每条数据能够点击跳转到当月详情页面,在element-ui-table 组件中使用的slot进行点击跳转。

动态将月数据加入label

// 假设json数据已得到

//每次查询记得初始化这两个数组
let list = [] // 
this.slotList = [] //
// 1. 获得最大值,避免label与数据对应不上
let maxLength = Math.max.apply(Math, json.map) => {
          
   
  return item.monthData.length
}
// 2.
for( const i in json) {
          
   
  let item = json[i]
  for( j in item) {
          
   
    // 得到月份作为label
    let month = item.monthData[j].key
    // 设置label的prop
    let prop = p+i
  	// 表数据
  	let monthValue = item.monthData[j].value
  	// 在最大值时添加label到element UI table组件Label中
  	if ( item.monthData === maxLength ) {
          
   
  	  let labelItem = {
          
   
  	  	prop:prop, 
  	  	label:month , //表头
  	  	width:180,
  	  	slot:true //由于之后要跳转
  	  }
  	  this.slotList.push(prop) // 为之后循环slot做准备
  	  list.push(labelItem)
  	}
  	// 设置表单每行数据 如 p0:12, p1:13, p2:14
  	json[i][prop] = monthValue 
  }
}
// 拼接表格label 这里的tableLabel 写成自己的表格的label
this.tableLabel = this.tableLabel.concat(list)

动态slot跳转 在element ui 中用的table 是 el-common-table 组件

// element ui 我在这就省略了表格的属性 加你自己的属性
<el-common-table >
<div
 v-for="(item, index) in slotList"
 slot-scope = "scope"
 :key="index"
 :slot="item">
 <!-- 跳转方法 以及值 -->
 <span  @click ="toPage(scope, row) "> {
          
   {
          
   scope.row[item] }} </span>
</div>	
</el-common-table >
(Emiited value instead of an instance of Error) Ambiguous combined usage of slot-scope and v-for on <div>(v-for takes higer priority)

这样写终端会报错但页面能正常加载。强迫症的我受不了这样!!!经过测试 以下为解决方法。

解决方法: ***

<el-common-table >
<template
 v-for="(item, index) in slotList"
 slot-scope = "scope"
 :slot="item">
 <!-- 跳转方法 以及值 -->
 <span :key="index" @click ="toPage(scope, row) "> {
          
   {
          
   scope.row[item]}} </span>
</template>	
</el-common-table >

欢迎各位大佬指正,讨论,交流

经验分享 程序员 微信小程序 职场和发展