IT俱乐部 JavaScript vue3 实现关于 el-table 表格组件的封装及调用方法

vue3 实现关于 el-table 表格组件的封装及调用方法

一、示例图:

二、组件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
<div class="sn-table">
    <div class="tag-list">
             
</div>
         
</div>
 
type TProps = {
  tableData: any[]
  columns: any[],
  colorType: number, // 颜色类型
  isExistSelect: boolean // 是否存在筛选项
}
const props = withDefaults(defineProps(), {})
const tableRowClassName = ({ rowIndex }: { rowIndex: number }) => {
  if (rowIndex % 2 === 1) {
    return props.colorType === 1 ? 'odd-row' : 'class-odd-row'
  } else {
    return props.colorType === 1 ? 'even-row' : 'class-even-row'
  }
}
 
.bg-scroll {
  border-radius: 10px;
  height: 96%;
  overflow-y: scroll;
  &::-webkit-scrollbar {
    width: 5px;
    height: 0 !important;
  }
  &::-webkit-scrollbar-thumb {
    border-radius: 10px;
    background: #eeeeee;
  }
}
.sn-table {
  padding: 0 10px 0 20px;
  :deep(.el-table) {
    color: #ffffff !important;
    tr {
      td {
        border: none;
        padding: 16px 0;
        font-size: 15px;
      }
    }
    th.el-table__cell {
      background: #141414 !important;
      border: none;
      color: #00B386;
      font-size: 14px;
      font-weight: 400;
    }
    .even-row {
      background-color: #333 !important;
    }
    .odd-row {
      background-color: #141414 !important;
    }
    .class-even-row {
      background-color: #333 !important;
    }
    .class-odd-row {
      background-color: #00B386 !important;
    }
  }
  :deep(.el-scrollbar__wrap--hidden-default) {
    background: #141414 !important;
  }
  :deep(.el-table--enable-row-hover) {
    .el-table__body {
      tr:hover>td.el-table__cell {
        color: #8C8C8C;
        background: #333 !important;
      }
    }
  }
  :deep(.el-table__inner-wrapper) {
    &::before {
      background-color: transparent;
    }
  }
  :deep(.el-table .ascending .sort-caret.ascending){
    border-bottom-color:#00B386 !important;
  }
  :deep(.el-table .descending .sort-caret.descending){
    border-top-color:#00B386 !important;
  }
  .ok-text{
    font-size: 35px;
    font-weight: 300;
  }
  .tag-list{
    width: 100%;
    padding: 2px 0;
    .tag-btn{
      border-radius: 5px;
      border: 1px solid #EF8714;
      color: #EF8714;
      padding: 1px 10px;
      margin-right: 15px;
      &:last-child{
        margin-right: 0;
      }
    }
  }
}
:deep(.el-progress){
  width: 185px;
  margin: 0 auto;
}
:deep(.el-progress__text){
  span{
    font-size: 16px;
  }
}
:deep(.el-progress-bar__outer){
  background: #D9D9D9;
}

三、页面调用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import { onMounted, ref } from 'vue'
import CanvasVideo from "@/components/CanvasVideo.vue"
const knowInfo = ref([])
const knowColumns = ref([])
onMounted(()=>{
    init()
})
//数据处理
const init = () => {
    const datas = ref([
        {studentName:'陈佳颖',correctRate:0,noAnswerCount:13},
        {studentName:'丁靖芸',correctRate:0,noAnswerCount:13},
        {studentName:'谷雨恒',correctRate:0,noAnswerCount:13},
        {studentName:'欧阳江源',correctRate:0,noAnswerCount:13},
        {studentName:'任行宽',correctRate:0,noAnswerCount:13},
        {studentName:'任彦宇',correctRate:0,noAnswerCount:13},
        {studentName:'王骁南',correctRate:0,noAnswerCount:13},
        {studentName:'吴骏扬',correctRate:0,noAnswerCount:13}
    ])
    if (datas && datas.length > 0) {
        datas.forEach((it: any, index:number) => {
            knowInfo.value.push({
                '行号': index+1,
                '姓名': it.studentName,
                '正确率': it.correctRate,
                '未答题数': it.noAnswerCount
            })
        })
        for (const key in knowInfo.value[0]) {
            knowColumns.value.push({
                keyName: key,
                width: key === '行号' ? 140 : null
            })
        }
    }
}

四、其他

(1)自定义标题

1
 

(2)自定义下标

1
{{$index+1}}

(3)自定义内容

1
<div>{{scope.row.name}}s</div>

(4)添加排序(升序、降序)

1
 

(5)多选与单选

1. 单选

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import { ref } from "vue"
const multipleTable = ref()
const handleList = ref([])
// 设置单选||显示高亮
const rowselect = (row:any) => {
  multipleTable.value.toggleRowSelection(row)
}
// 选择多个单选框,只取最后选中的那一个
const selectGroupChange = (row:any) => {
  if (row.length > 1) {
    multipleTable.value.clearSelection()
    multipleTable.value.toggleRowSelection(row.pop())
    return
  }
  if (row.length == 1) {
    handleList.value = row
  } else {
    handleList.value = []
  }
}
 
// 隐藏表头选择框
:deep(.el-table__header){
  .el-checkbox{
    display: none;
  }
}

2. 多选

1
2
3
4
// 选择多个选择框
const handleSelectionChange = (selecteds: any, row: any) => {}
// 全选
const handleAllChange= (row:any) => {}

五、实例(实现树形数据与懒加载)

示例图:通过点击当前节点,调用接口展示下一节点,实现列表的增删改查

1、添加修改组件 EditForm.vue

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
<div>
     
</div>
 
import { getChildrens, getDictionaryInfo, EditDictionary } from '@/api/dictionary'
import rules from '@/utils/rules'
export default {
  props: {
    id: {
      type: Number,
      default: 0
    },
    title: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      menuTree: [], // 字典树
      rules: rules,
      formLabelWidth: '120px',
      size: 'small',
      loading: false,
      form: {
        id: this.id,
        parentId: 0,
        parentDictionaryName: '',
        dictionaryCode: '',
        dictionaryName: '',
        remark: '',
        deleteState: true
      }
    }
  },
  created() {
    this.fetchInitData()
  },
  methods: {
    handlePagedCallback() {
      this.$emit('handlePagedCallback')
    },
    handleSubmitForm() {
      this.$refs['menuEditForm'].validate((valid) => {
        if (valid) {
          this.loading = true
          EditDictionary(this.form).then((res) => {
            this.loading = false
            if (res.code === 200) {
              if (res.data) {
                this.$message.success('操作成功')
                this.handlePagedCallback()
              } else {
                this.$message.error('操作失败')
              }
            } else {
              this.$message.error(res.message)
            }
          })
        }
      })
    },
    handleResetForm() {
      if (this.$refs['menuEditForm']) {
        this.$refs['menuEditForm'].resetFields()
      }
    },
    fetchInitData() {
      getChildrens().then((res) => {
        if (res.code === 200) {
          this.menuTree = JSON.parse(JSON.stringify(res.data).replace(/id/g, 'value').replace(/dictionaryName/g, 'label'))
          this.fetchFormData()
        }
      })
    },
    fetchFormData() {
      this.handleResetForm()
      if (this.id !== 0) {
        const id = { Id: this.id }
        getDictionaryInfo(id).then((res) => {
          if (res.code === 200) {
            this.form = Object.assign(this.form, res.data)
          }
        })
      }
    }
  }
}

2、主页面 index.vue

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
<div class="app-container">
    <div class="search-container">
       
      查询
</div>
    <div class="toolbar-container">
       
      新增修改删除
</div>
    <div class="dialog-container">
      <span class="dialog-footer">
          取 消确 定</span>
       
</div>
  </div>
 
import Pagination from '@/components/Pagination'
import EditForm from './EditForm'
import { getDictionaryNext, getDictionaryRoute, DeleteDictionaryRoute } from '@/api/dictionary'
export default {
  components: { Pagination, EditForm },
  data() {
    return {
      search: {
        keyword: ''
      },
      searchId: 0,
      // 表格数据
      table: {
        data: [],
        selectRows: [],
        border: false
      },
      currChildren: [],
      // 分页数据
      pagination: {
        index: 1,
        size: 20,
        total: 0
      },
      // 弹出层
      dialog: {
        close: false, // 是否关闭
        edit: {
          id: 0,
          title: '修改字典', // 弹出层title
          visible: false, // 弹出层是否显示
          width: '800px' // 弹出层宽度
        }
      },
      layzNode: null,
      layztreeNode: null,
      layzresolve: null
    }
  },
  created() {
    this.getDictionaryList()
  },
  methods: {
    lazyload(tree, treeNode, resolve) {
      if (tree) {
        var data = {
          Id: tree.id
        }
        getDictionaryNext(data).then((res) => {
          if (res.code === 200) {
            this.layzNode = tree
            this.layztreeNode = treeNode
            this.layzresolve = resolve
            resolve(res.data)
          }
        })
      }
    },
    Submit() {
      this.$refs.Submit.handleSubmitForm()
    },
    // 勾选
    handleSelectionChange(selection) {
      this.table.selectRows = selection
    },
    // 新增
    AddDialog() {
      this.dialog.edit.id = 0
      this.dialog.edit.title = '添加字典'
      this.dialog.edit.visible = true
    },
    // 修改
    EditDialog() {
      if (this.table.selectRows.length !== 1) {
        this.$message.warning('请选择要修改的字典')
      } else {
        this.dialog.edit.id = this.table.selectRows[0].id
        this.dialog.edit.title = '修改字典'
        this.dialog.edit.visible = true
      }
    },
    // 修改成功回调
    handleEditCallback() {
      this.dialog.edit.visible = false
      this.dialog.edit.id = 0
      this.$nextTick(() => {
        this.$set(this.$refs.myTable.store.states.lazyTreeNodeMap, this.layzNode.id, [])
        this.lazyload(this.layzNode, this.layztreeNode, this.layzresolve)
        this.getDictionaryList()
      })
    },
    // 删除
    handleDelete() {
      if (this.table.selectRows.length === 0) {
        this.$message.warning('未勾选记录')
        return
      }
      const ids = []
      this.table.selectRows.forEach((it) => {
        ids.push(it.id)
      })
      this.$confirm('此操作将永久删除勾选记录, 是否继续?').then(() => {
        DeleteDictionaryRoute(ids).then((res) => {
          if (res.code === 200) {
            if (res.data) {
              this.$nextTick(() => {
                this.getDictionaryList()
                this.$set(this.$refs.myTable.store.states.lazyTreeNodeMap, this.layzNode.id, [])
                this.lazyload(this.layzNode, this.layztreeNode, this.layzresolve)
              })
              this.$message.success('操作成功')
            } else {
              this.$message.error('操作失败')
            }
          } else {
            this.$message.error(res.message)
          }
        })
      })
    },
    // 列表接口
    getDictionaryList() {
      var data = {
        searchName: this.search.keyword,
        searchId: this.searchId,
        pageIndex: this.pagination.index,
        pageSize: this.pagination.size
      }
      getDictionaryRoute(data).then((res) => {
        if (res.code === 200) {
          this.pagination.total = res.data.total
          this.table.data = res.data.data
        }
      })
    },
    // 重载表格
    handleReloadPaged() {
      this.pagination.index = 1
      this.getDictionaryList()
    },
    // 分页变更
    handlePaginationChange(data) {
      this.pagination.index = data.current
      this.pagination.size = data.pageSize
      this.getDictionaryList()
    }
  }
}

       希望我的愚见能够帮助你哦~,若有不足之处,还望指出,你们有更好的解决方法,欢迎大家在评论区下方留言支持,大家一起相互学习参考呀~

到此这篇关于vue3 实现关于 el-table 表格组件的封装以及调用的文章就介绍到这了,更多相关vue3 el-table 表格组件封装内容请搜索IT俱乐部以前的文章或继续浏览下面的相关文章希望大家以后多多支持IT俱乐部!

本文收集自网络,不代表IT俱乐部立场,转载请注明出处。https://www.2it.club/navsub/js/12321.html
上一篇
下一篇
联系我们

联系我们

在线咨询: QQ交谈

邮箱: 1120393934@qq.com

工作时间:周一至周五,9:00-17:30,节假日休息

关注微信
微信扫一扫关注我们

微信扫一扫关注我们

返回顶部