vue 结合 element-ui 实现强大的后台管理系统表格组件

简介

表格作为后台管理系统的最重要的基础组件之一,功能越强大,后续所做的开发量就越小,这里把常见的提炼出来,分享给大家。基础功能支持 loading,分页,按钮操作,数据格式化,数据选择等。

主要依赖说明 (先安装,步骤略)

1
{
2
  "element-ui": "2.11.1",
3
  "vue": "^2.6.10",
4
  "vue-router": "^3.0.1",
5
  "font-awesome": "4.7.0"
6
}

正文

1.组件

src/components/Table/index.vue

1
<template>
2
  <div>
3
    <!-- 表头 -->
4
    <div v-if="title" class="table-title">{{ title }}</div>
5
6
    <!-- 表格主体 -->
7
    <el-table
8
      :ref="ref"
9
      v-loading="listLoading"
10
      :data="tableData"
11
      :border="isBorder"
12
      :element-loading-text="loadingText"
13
      :header-cell-style="{ backgroundColor: '#e5e9f2', color: '#333' }"
14
      highlight-current-row
15
      stripe
16
      size="small"
17
      empty-text="暂无数据"
18
      @selection-change="handleSelectionChange"
19
    >
20
      <!-- 多选配置 -->
21
      <el-table-column
22
        v-if="isSelection"
23
        type="selection"
24
        width="55"
25
      ></el-table-column>
26
27
      <!-- 表格索引 -->
28
      <el-table-column
29
        v-if="isShowNumber"
30
        fixed="left"
31
        type="index"
32
        :index="tableIndex"
33
      ></el-table-column>
34
35
      <!-- 表格行  item.showOverflowTooltip 设置表格文字过长显示省略号 -->
36
      <el-table-column
37
        v-for="(item, index) in config"
38
        :key="index"
39
        :prop="item.prop"
40
        :label="item.label"
41
        :width="item.width"
42
        :show-overflow-tooltip="item.showOverflowTooltip"
43
      >
44
        <template slot-scope="scope">
45
          <!-- format = img, 显示图片 -->
46
          <span v-if="item.format == 'img'">
47
            <img
48
              title="点击查看大图"
49
              alt="图片"
50
              class="image-size"
51
              :src="scope.row[item.prop]"
52
            />
53
          </span>
54
55
          <!-- format = timestamp, 把时间戳转换成YYYY-MM-dd HH:mm:ss ,parseTime过滤器后文会提到   -->
56
          <span v-else-if="item.format == 'timestamp'"
57
            >{{ scope.row[item.prop] | parseTime }}</span
58
          >
59
60
          <!-- format = money, 显示金额 -->
61
          <span v-else-if="item.format == 'money'"
62
            >{{ '¥'+scope.row[item.prop] }}</span
63
          >
64
65
          <!-- format = rate, 显示比例 -->
66
          <span v-else-if="item.format == 'rate'"
67
            >{{ scope.row[item.prop]+"%" }}</span
68
          >
69
70
          <!-- format = number, 显示数字-->
71
          <span v-else-if="item.format == 'number'"
72
            >{{ Number(scope.row[item.prop]) }}</span
73
          >
74
75
          <!-- format = a, 网页跳转 -->
76
          <span v-else-if="item.format == 'a'">
77
            <u class="link">
78
              <a :href="scope.row[item.prop]" target="_blank"
79
                >{{ scope.row[item.prop] }}</a
80
              >
81
            </u>
82
          </span>
83
84
          <!-- 需要添加其他数据处理,继续添加 v-else-if="item.format == ''" 就好 -->
85
86
          <!-- 没有format -->
87
          <span v-else>{{ scope.row[item.prop] }}</span>
88
        </template>
89
      </el-table-column>
90
91
      <!-- 表格操作按钮栏 -->
92
      <el-table-column
93
        v-if="isHasButtons"
94
        class="clearfix"
95
        :width="optionColumnWidth+'px'"
96
        fixed="right"
97
        label="操作"
98
      >
99
        <template slot-scope="scope">
100
          <!-- 基本操作 -->
101
          <span
102
            v-for="(option, index) in getOptionsName(scope.row.buttonKey).slice(0,buttonCount)"
103
            :key="index"
104
            class="button-margin-left"
105
          >
106
            <el-button
107
              size="small"
108
              :type="index == 0 ? 'primary' : ''"
109
              @click="handleClickOption(scope.$index, scope.row, option,$event)"
110
            >
111
              <span v-html="getButtonHtml(option)"></span>
112
            </el-button>
113
          </span>
114
115
          <!-- 更多操作 -->
116
          <el-dropdown
117
            v-if="getOptionsName(scope.row.buttonKey).length > buttonCount"
118
            trigger="click"
119
          >
120
            <span class="el-dropdown-link">
121
              更多
122
              <i class="el-icon-arrow-down el-icon--right"></i>
123
            </span>
124
            <el-dropdown-menu slot="dropdown" class="custom-dropdown-menu">
125
              <el-dropdown-item
126
                v-for="(option, index) in getOptionsName(scope.row.buttonKey).slice(buttonCount)"
127
                :key="index"
128
                class="custom-dropdown-menu-item"
129
              >
130
                <el-button
131
                  size="small"
132
                  @click="handleClickOption(scope.$index, scope.row, option,$event)"
133
                >
134
                  <span v-html="getButtonHtml(option)"></span>
135
                </el-button>
136
              </el-dropdown-item>
137
            </el-dropdown-menu>
138
          </el-dropdown>
139
        </template>
140
      </el-table-column>
141
    </el-table>
142
143
    <!-- 分页组件 -->
144
    <div v-if="isShowPagination && total > 0" class="pagination-container">
145
      <el-pagination
146
        background
147
        layout="total, sizes, prev, pager, next, jumper"
148
        :current-page="page"
149
        :page-sizes="pageSizeList"
150
        :page-size="limit"
151
        :total="total"
152
        @current-change="handleCurrentChange"
153
        @size-change="handleSizeChange"
154
      ></el-pagination>
155
    </div>
156
  </div>
157
</template>
158
159
<script>
160
  export default {
161
    name: "AppTable",
162
    props: {
163
      // 是否需要序号
164
      isShowNumber: {
165
        type: Boolean,
166
        default: true
167
      },
168
      // 是否需要翻页组件
169
      isShowPagination: {
170
        type: Boolean,
171
        default: true
172
      },
173
      // 是否需要栅格
174
      isBorder: {
175
        type: Boolean,
176
        default: true
177
      },
178
      // 是否是多选表格,默认非多选 :ref="'multipleTable'"
179
      isSelection: {
180
        type: Boolean,
181
        default: false
182
      },
183
      // 是否有操作按钮
184
      isHasButtons: {
185
        type: Boolean,
186
        default: true
187
      },
188
      // 表头名称
189
      title: {
190
        type: String
191
      },
192
      // 表格数据
193
      tableData: {
194
        type: Array,
195
        required: true
196
      },
197
      // 表格配置信息
198
      config: {
199
        type: Array,
200
        required: true
201
      },
202
      // loading提示框
203
      loadingText: {
204
        type: String,
205
        default: "加载中..."
206
      },
207
      // loading状态
208
      loadingStatus: {
209
        type: Boolean,
210
        default: false
211
      },
212
      // 表格查询列表参数
213
      listQueryParams: {
214
        type: Object
215
      },
216
      // 根据当前行的状态显示按钮的名称
217
      buttonsName: {
218
        type: Object
219
      },
220
      // 操作列表宽度
221
      optionColumnWidth: {
222
        type: Number,
223
        default: 100
224
      },
225
      // 分页数据
226
      pageSizeList: {
227
        type: Array,
228
        default: function() {
229
          return [10, 20, 30, 50, 100];
230
        }
231
      },
232
      // 显示的操作栏按钮个数,多余的显示在dropdown里
233
      buttonCount: {
234
        type: Number,
235
        default: 2
236
      }
237
    },
238
239
    computed: {
240
      // 看是否是多选表格
241
      ref: function() {
242
        return this.isSelection ? "multipleTable" : undefined;
243
      },
244
      // 第几页
245
      page: function() {
246
        return this.listQueryParams.page || 1;
247
      },
248
      // 每页数据数
249
      limit: function() {
250
        return this.listQueryParams.limit || 10;
251
      },
252
      // 数据总数
253
      total: function() {
254
        return this.listQueryParams.total || 0;
255
      },
256
      // 获取当前loading的状态
257
      listLoading: function() {
258
        return this.loadingStatus;
259
      }
260
    },
261
    methods: {
262
      // 根据按钮的名称,获取按钮的html样式,让按钮有个图标,这里使用的是font-awesome,要使用的话先安装
263
      getButtonHtml(name) {
264
        let className;
265
        switch (name) {
266
          case "查看":
267
            className = "eye";
268
            break;
269
          case "编辑":
270
            className = "pencil";
271
            break;
272
          case "审核":
273
            className = "check-circle";
274
            break;
275
          case "置顶":
276
            className = "arrow-circle-o-up";
277
            break;
278
          case "取消置顶":
279
            className = "times-circle";
280
            break;
281
          case "推荐":
282
            className = "thumbs-o-up";
283
            break;
284
          case "上线":
285
            className = "space-shuttle";
286
            break;
287
          case "下线":
288
            className = "space-shuttle";
289
            break;
290
          case "删除":
291
            className = "times-circle-o";
292
            break;
293
          case "分析":
294
            className = "bar-chart";
295
            break;
296
          case "排序":
297
            className = "sort";
298
            break;
299
        }
300
        if (className) {
301
          return `<span><i class="fa fa-${className}"></i> ${name}</span>`;
302
        } else {
303
          return name;
304
        }
305
      },
306
307
      // 获取当前操作的按钮组
308
      getOptionsName(key) {
309
        return this.buttonsName[key] || [];
310
      },
311
312
      // 点击按钮传递给父组件
313
      handleClickOption(index, row, option) {
314
        this.$emit("subOpitonButton", index, row, option);
315
      },
316
317
      // 表格选择分发事件
318
      handleSelectionChange(val) {
319
        this.$emit("subSelected", val);
320
      },
321
322
      // 改变翻页组件中每页数据总数
323
      handleSizeChange(val) {
324
        this.listQueryParams.limit = val;
325
        // 改变翻页数目,将页面=1
326
        this.listQueryParams.page = 1;
327
        this.$emit("update:listQueryParams", this.listQueryParams);
328
        this.$emit("subClickPagination", this.listQueryParams);
329
      },
330
331
      // 跳到当前是第几页
332
      handleCurrentChange(val) {
333
        this.listQueryParams.page = val;
334
        this.$emit("update:listQueryParams", this.listQueryParams);
335
        this.$emit("subClickPagination", this.listQueryParams);
336
      },
337
338
      // 重写索引生成方法
339
      tableIndex(index) {
340
        const i = (this.page - 1) * this.limit + index + 1;
341
        return i;
342
      }
343
    }
344
  };
345
</script>
346
347
<style lang="scss" scoped>
348
  .image-size {
349
    width: 30px;
350
    height: 30px;
351
    cursor: pointer;
352
  }
353
  .table-title {
354
    margin-top: 10px;
355
    font-size: 18px;
356
  }
357
  .el-dropdown {
358
    cursor: pointer;
359
    margin-left: 20px;
360
361
    .el-dropdown-link {
362
      user-select: none;
363
      cursor: pointer;
364
    }
365
  }
366
367
  .button-margin-left {
368
    margin-left: 8px;
369
  }
370
371
  .link {
372
    cursor: pointer;
373
    color: #4876ff;
374
  }
375
</style>
376
377
<style lang="scss">
378
  .el-table {
379
    .el-table__empty-block {
380
      height: unset;
381
    }
382
  }
383
  .custom-dropdown-menu {
384
    cursor: pointer;
385
    .custom-dropdown-menu-item {
386
      margin-top: 10px;
387
      text-align: center;
388
    }
389
    .el-dropdown-menu__item:focus,
390
    .el-dropdown-menu__item:not(.is-disabled):hover {
391
      background-color: #fff;
392
      color: #fff;
393
    }
394
  }
395
</style>

2.使用

1
<template>
2
  <div>
3
    <el-row class="margin-top-10">
4
      <el-card>
5
        <app-table
6
          :list-query-params.sync="listQueryParams"
7
          v-bind="tableAttrs"
8
          v-on="tableEvent"
9
        />
10
      </el-card>
11
    </el-row>
12
  </div>
13
</template>
14
15
<script>
16
  import AppTable from "@/components/Table";
17
  // 定义的接口根据自己项目更换
18
  import TalentServe from "@/api/talent";
19
  //  表格查询参数
20
  const DefaultTableQuery = {
21
    page: 1,
22
    limit: 10,
23
    total: 0
24
  };
25
26
  export default {
27
    name: "UserList",
28
    components: {
29
      AppTable
30
    },
31
    data() {
32
      return {
33
        // 表格加载loading
34
        loadingStatus: false,
35
        //  操作栏宽度
36
        optionWidth: 280,
37
        // 表头配置  prop字段和服务端数据给的字段一致
38
        tableConfig: [
39
          {
40
            label: "昵称",
41
            width: "120px",
42
            prop: "nickname"
43
          },
44
          {
45
            label: "头像",
46
            width: "120px",
47
            prop: "headImgUrl",
48
            // 显示图片
49
            format: "img"
50
          },
51
          {
52
            label: "手机号",
53
            width: "120px",
54
            prop: "mobile"
55
          },
56
          {
57
            label: "注册时间",
58
            width: "140px",
59
            prop: "registrationDate",
60
            // 显示时间
61
            format: "timestamp"
62
          },
63
          {
64
            label: "邀请人",
65
            width: "80px",
66
            prop: "inviterUser"
67
          },
68
          {
69
            label: "收益金额",
70
            width: "120px",
71
            prop: "integrals",
72
            format: "money"
73
          },
74
          // 最后一个不给宽度让表格自适应
75
          {
76
            label: "类型",
77
            prop: "customIsExpressive"
78
          }
79
        ],
80
        // 参数
81
        listQueryParams: { ...DefaultTableQuery },
82
        // 列表数据
83
        tableData: [],
84
        // url参数
85
        params: {
86
          pageInfo: {
87
            pageSize: 10,
88
            pageNo: 1
89
          }
90
        },
91
        // 操作栏按钮
92
        buttonsName: {
93
          normal: ["查看", "编辑", "设为可提现"],
94
          special: ["查看", "编辑", "取消可提现"]
95
        },
96
        // 选择数据
97
        selectData: [],
98
        // 操作数据
99
        operationalData: {}
100
      };
101
    },
102
    computed: {
103
      // 表格属性
104
      tableAttrs() {
105
        return {
106
          // 表头配置
107
          config: this.tableConfig,
108
          // 表格数据
109
          tableData: this.tableData,
110
          // loading
111
          loadingStatus: this.loadingStatus,
112
          // 按钮名称
113
          buttonsName: this.buttonsName,
114
          // 操作栏宽度
115
          optionColumnWidth: this.optionWidth,
116
          // 是否需要选择
117
          isSelection: true
118
        };
119
      },
120
      // 表格事件
121
      tableEvent() {
122
        return {
123
          // 按钮操作
124
          subOpitonButton: this.handleTableOption,
125
          // 分页
126
          subClickPagination: this.handleRefreshList,
127
          // 表格数据选择
128
          subSelected: this.handleSelectionChange
129
        };
130
      }
131
    },
132
    created() {
133
      this.getList();
134
    },
135
    methods: {
136
      // 获取列表
137
      async getList() {
138
        try {
139
          // 表格加载loading
140
          this.loadingStatus = true;
141
          // 分页数据作为参数给服务端
142
          this.params.pageInfo.pageSize = this.listQueryParams.limit;
143
          this.params.pageInfo.pageNo = this.listQueryParams.page;
144
          // 发送请求,请求到的数据格式见下文,
145
          const { data, cntData } = await TalentServe.getTalentList(
146
            this.params
147
          );
148
          const tableData = data || [];
149
          tableData.forEach(item => {
150
            if (item.isExpressive === "1") {
151
              // 给每一行设置buttonKey对应于data里定义的buttonsName的key值
152
              // buttonsName: {
153
              //   normal: ['查看', '编辑', '设为可提现'],
154
              //   special: ['查看', '编辑', '取消可提现']
155
              // },
156
              //
157
              item.buttonKey = "special";
158
            } else {
159
              item.buttonKey = "normal";
160
            }
161
            // 修改显示的数据
162
            item.customIsExpressive =
163
              item.isExpressive === "1" ? "可提现" : "不可提现";
164
          });
165
          // 分页组件显示  this.listQueryParams.total 值大于0才会出现
166
          this.listQueryParams.total = cntData;
167
          // 数据给表格
168
          this.tableData = data;
169
          this.loadingStatus = false;
170
        } catch (error) {
171
          console.log(error);
172
        }
173
      },
174
175
      // 表格操作功能 index:表格索引, row:表格行数据, option:按钮名称
176
      handleTableOption(index, row, option) {
177
        this.operationalData = { ...row };
178
        if (option === "查看") {
179
          console.log(index, row, option);
180
        } else if (option === "编辑") {
181
          console.log(index, row, option);
182
        } else if (option === "设为可提现") {
183
          console.log(index, row, option);
184
        } else if (option === "取消可提现") {
185
          console.log(index, row, option);
186
        }
187
      },
188
189
      // 选择的数据回调
190
      handleSelectionChange(data) {
191
        console.log(data);
192
      },
193
194
      // 分页操作
195
      handleRefreshList() {
196
        this.getList();
197
      }
198
    }
199
  };
200
</script>

3.请求到的服务端数据

1
{
2
  "result": true,
3
  "message": null,
4
  "data": [
5
    {
6
      "headImgUrl": "https://wx.qlogo.cn/mmopen/vi_32/RYIWG1XDAOVbAXHWONRiab639VRyr7cKQcCibXz8s2m4xhuDmDYo8XxGde0NiaAJ5vy8SHznDIoQ7mBtLibg9sicia0w/132",
7
      "nickname": "万马奔腾",
8
      "mobile": "13892188637",
9
      "registrationDate": 1556666683000,
10
      "userId": "0172cf8bbda841dca100aa8b30b1d58e",
11
      "inviterUser": null,
12
      "inviterId": null,
13
      "friendsNum": 0,
14
      "friendsNumSum": 0,
15
      "integrals": 0.0,
16
      "isExpressive": ""
17
    },
18
    {
19
      "headImgUrl": "https://wx.qlogo.cn/mmopen/vi_32/DYAIOgq83eptKEXTYEu3Ne3pF7OcUvibUBY0hSibibH7SRTNxN9x7522mYQZ63ZEBF8nbjty1NN60ScPicsuGGrrtQ/132",
20
      "nickname": "    水目菊  ",
21
      "mobile": "15991695887",
22
      "registrationDate": 1560258459000,
23
      "userId": "021c02454ea64fab8640f1fa25e18637",
24
      "inviterUser": null,
25
      "inviterId": null,
26
      "friendsNum": 0,
27
      "friendsNumSum": 0,
28
      "integrals": 0.0,
29
      "isExpressive": ""
30
    },
31
    {
32
      "headImgUrl": "https://wx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTKLvV2y1XiaJJDfibB7zlqaTudCEsiapR8iaShFykZ2SgVD24zxYve5kPLvQooFy4ibePbpcribtZJVXlEQ/132",
33
      "nickname": "老要",
34
      "mobile": "",
35
      "registrationDate": 1563934025000,
36
      "userId": "024bc4c4f5db418499d3633621b2b834",
37
      "inviterUser": null,
38
      "inviterId": null,
39
      "friendsNum": 0,
40
      "friendsNumSum": 0,
41
      "integrals": 0.0,
42
      "isExpressive": ""
43
    },
44
    {
45
      "headImgUrl": "https://wx.qlogo.cn/mmhead/2yfPLY1YiaibeyxYwultf0Z7VNea1H1icXrV9pQcldEHTc/132",
46
      "nickname": "林群梦",
47
      "mobile": "",
48
      "registrationDate": 1557438206000,
49
      "userId": "035826db900d4b7a912664119189b6f1",
50
      "inviterUser": null,
51
      "inviterId": null,
52
      "friendsNum": 0,
53
      "friendsNumSum": 0,
54
      "integrals": 0.0,
55
      "isExpressive": ""
56
    },
57
    {
58
      "headImgUrl": "https://wx.qlogo.cn/mmopen/vi_32/DYAIOgq83eqF8zPxScdIGo0nK7so6bzFibRF1sEXrT404XUN2gcfFRTB1pcCaZPBUr9lGKGibbiaUWVTOw7HpaNNg/132",
59
      "nickname": "贺励",
60
      "mobile": "",
61
      "registrationDate": 1563490853000,
62
      "userId": "035b59b061454336953d47822c7b0406",
63
      "inviterUser": null,
64
      "inviterId": null,
65
      "friendsNum": 0,
66
      "friendsNumSum": 0,
67
      "integrals": 0.0,
68
      "isExpressive": ""
69
    },
70
    {
71
      "headImgUrl": "https://wx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTLsymhiblxYck4YOUxdtpZOib12KgJj6ciaJxV2ibtia92YODBhC05YL8rCNKQQjc09tZTP6xBxkT0qK5Q/132",
72
      "nickname": "乾坤",
73
      "mobile": "15091593977",
74
      "registrationDate": 1557153760000,
75
      "userId": "03a91cb5a60f4f02bf22b1e9e179258d",
76
      "inviterUser": null,
77
      "inviterId": null,
78
      "friendsNum": 0,
79
      "friendsNumSum": 0,
80
      "integrals": 0.0,
81
      "isExpressive": ""
82
    },
83
    {
84
      "headImgUrl": "https://wx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTJpTy32D4vRETGtricKwfhx3kiaTJcibRyMFg5KvSENibeWKE0Xq4gZ9ZyicZLvkUQ4RSVBpwwiaOhW5lLg/132",
85
      "nickname": "鸿涛",
86
      "mobile": "13909256676",
87
      "registrationDate": 1556680061000,
88
      "userId": "03d7811ea5cb4e1e851c5245128674c2",
89
      "inviterUser": "三百千.刘震",
90
      "inviterId": "b33b3879531d41e4bc19b629cb7c7cb8",
91
      "friendsNum": 0,
92
      "friendsNumSum": 0,
93
      "integrals": 408.0,
94
      "isExpressive": ""
95
    },
96
    {
97
      "headImgUrl": "https://wx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTKLuf2cK1w7sN3qD0cM4XvbYWnJJa5hibyUKGv0oPzG0LT1UjFvTTRuibOCTvxDibQdU9icFxK1TZOSHQ/132",
98
      "nickname": "格格",
99
      "mobile": "",
100
      "registrationDate": 1560569395000,
101
      "userId": "04346cf9a9284d058f71a59de4b37e49",
102
      "inviterUser": null,
103
      "inviterId": null,
104
      "friendsNum": 0,
105
      "friendsNumSum": 0,
106
      "integrals": 0.0,
107
      "isExpressive": ""
108
    },
109
    {
110
      "headImgUrl": "https://wx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTJ9PZJVYXlalZyggdlVpCoPJcvIHrh1eN3SRRoTkdBgGjhQwrBQMibYma0xkdf6BlaKHLdv5YzM1AA/132",
111
      "nickname": "水木清华",
112
      "mobile": "13359265165",
113
      "registrationDate": 1557146507000,
114
      "userId": "05f3c11d67044e30a61abd79fc542c36",
115
      "inviterUser": null,
116
      "inviterId": null,
117
      "friendsNum": 0,
118
      "friendsNumSum": 0,
119
      "integrals": 0.0,
120
      "isExpressive": ""
121
    },
122
    {
123
      "headImgUrl": "https://wx.qlogo.cn/mmopen/vi_32/PiajxSqBRaEJiaXZyZ6Tnv4z7YgvVXRvuONlTc9DNQVS0d52HnScISc77XGKawodayVib3fnLwV9trSDlUkRKwHRw/132",
124
      "nickname": "王鸣@ODIN",
125
      "mobile": "",
126
      "registrationDate": 1560861936000,
127
      "userId": "07087c0478ae43b18765272fbb4aa5e1",
128
      "inviterUser": null,
129
      "inviterId": null,
130
      "friendsNum": 0,
131
      "friendsNumSum": 0,
132
      "integrals": 0.0,
133
      "isExpressive": ""
134
    }
135
  ],
136
  "cntPage": 33,
137
  "cntData": 323
138
}

3.补充表格组件用的过滤器(自行注册,步骤略)

1
export function parseTime(time, cFormat) {
2
  if (arguments.length === 0) {
3
    return null;
4
  }
5
6
  if ((time + "").length === 10) {
7
    time = +time * 1000;
8
  }
9
10
  const format = cFormat || "{y}-{m}-{d} {h}:{i}:{s}";
11
  let date;
12
  if (typeof time === "object") {
13
    date = time;
14
  } else {
15
    date = new Date(parseInt(time));
16
  }
17
  const formatObj = {
18
    y: date.getFullYear(),
19
    m: date.getMonth() + 1,
20
    d: date.getDate(),
21
    h: date.getHours(),
22
    i: date.getMinutes(),
23
    s: date.getSeconds(),
24
    a: date.getDay()
25
  };
26
  const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
27
    let value = formatObj[key];
28
    if (key === "a") {
29
      return ["一", "二", "三", "四", "五", "六", "日"][value - 1];
30
    }
31
    if (result.length > 0 && value < 10) {
32
      value = "0" + value;
33
    }
34
    return value || 0;
35
  });
36
  return time_str;
37
}

4.效果展示
在这里插入图片描述