elementUI+vue表格組件(支持多選、分頁、選中回顯、搜索、增刪改)

功能

本組件能實(shí)現(xiàn)表格多選,分頁,分頁選中回顯,新建、刪除、修改、查詢。

寫在前,有問題歡迎問,有更好的建議歡迎留言~~~
使用時(shí)要注意將后臺(tái)接口的情況,根據(jù)情況修改代碼。
但是!?。?!
不要只做復(fù)制粘貼,報(bào)錯(cuò)了就來亂噴的噴子

如果對(duì)你有幫助,希望你給我喜歡 !收藏!git上點(diǎn)星星!哈哈哈哈或哈哈哈哈(不要臉了)

實(shí)現(xiàn)效果

1.png
2.png
3.png

思路要點(diǎn)

將組件的操作產(chǎn)生的參數(shù)全部返回父組件,由父組件處理接口數(shù)據(jù)的交互
這樣就可以提高表格組件的多樣性,提高耦合程度,和高復(fù)用性,不必因?yàn)榻涌谔幚矸绞讲煌匦戮帉懡M件。
比如點(diǎn)擊確定按鈕請(qǐng)求接口,不同的功能會(huì)調(diào)用不同接口地址,如果將接口請(qǐng)求都放入組件內(nèi),那么下次復(fù)用的時(shí)候就會(huì)改組件的代碼。如果是多人維護(hù),那大大增加的出bug的風(fēng)險(xiǎn)。

廢話不多說,上代碼

父組件

模板代碼,主要是用tableData傳輸數(shù)據(jù),其他@方法來接收參數(shù)

<template>
  <div>
    <checkboxTable
      :tableData="tableData" @Search="Search"
      @editline="editline" @deleteline="deleteline"
      @pageChange="pageChange" @createInfor="createInfor">
    </checkboxTable>
  </div>
</template>

引入組件

import checkboxTable from '@/components/common/checkboxTable'

數(shù)據(jù)結(jié)構(gòu)和引用組件

   components: {
      checkboxTable
      //引用組件
    },
    data: () => ({
      //向table傳值
      tableData: {
        //是否顯示組件
        isShow: true,
        //是否顯示新建彈框
        dialogTableVisible: false,
        //表格行項(xiàng)目列表和總條目數(shù)
        lineItems: {
          items: [],
          totalCount: 0,
        },
        //表格頭部信息
        table: {
          header: {},
        },
        //存放搜索的key數(shù)組
        search: [],
        //分頁器
        fenye: {
          pageIndex: 1,
          pageSize: 10,
        },
      },
    }),

將接收的數(shù)據(jù)進(jìn)行處理,然后傳入表格組件

     //處理表格數(shù)據(jù)
      dealTableData(obj) {
        //賦值列表
        this.tableData.lineItems = obj;
        //創(chuàng)建表頭名稱
        this.tableData.table.header = {
          "name": "姓名", "sex": "性別", "age": "年齡",
        };
        //搜索條件的key
        this.tableData.search = [
          {name: "姓名", id: "name", value: ""},
          {name: "年齡", id: "age", value: ""}];
      },

接收表格組件參數(shù)的示例函數(shù),具體情況要根據(jù)后臺(tái)接口來寫

      //新建條目
      createInfor(details) {
        this.$post("新建接口", details, {
          emulateJSON: true
        }).then((response) => {
          if (response.code === 'success') {
            this.$message({message: '創(chuàng)建成功', type: 'success'});
            //請(qǐng)求成功后將彈窗關(guān)閉
            this.tableData.dialogTableVisible = false;
            //重新請(qǐng)求列表接口,刷新數(shù)據(jù)
            this.getTableData();
          } else {
            this.$message({message: '創(chuàng)建失敗', type: 'warning'});
          }
        }, err => {
          console.log(err);
        });
      },
      //請(qǐng)求基礎(chǔ)表格數(shù)據(jù)
      getTableData(msg) {
        this.$post("表格列表接口", {
          "page": this.tableData.fenye.pageIndex,
          "rows": this.tableData.fenye.pageSize
        }).then((response) => {
          console.log(response)
          if (response.code === 'success') {
            this.$message({message: response.msg, type: 'success'});
            //將數(shù)據(jù)傳入處理函數(shù)
            this.dealTableData(response.data)
            return
          } else {
            this.$message({message: response.msg, type: 'warning'});
          }
        }, err => {
          console.log(err);
        });
      },

表格組件

沒啥說的,代碼注釋里邊都有。

哦,有一點(diǎn)要說
分頁頁碼回顯的時(shí)候,有時(shí)候不會(huì)重新渲染,所以要在分頁器上加個(gè)v-if強(qiáng)制重新渲染
uuid這個(gè)插件,視項(xiàng)目情況引用

<template>
  <div>
    <div style="width:100%;">
      <div class=" clearfix" style="margin-bottom: 30px">
        <el-row>
          <el-col :span="6" v-for="(item,index) in tableData.search">
            <el-col :span="6" style="line-height: 40px;">{{item.name}}</el-col>
            <el-col :span="12">
              <el-input placeholder="" v-model=item.value
                        @keyup.enter.native="Search()"></el-input>
            </el-col>
          </el-col>
          <el-col :span="8">
            <el-button @click="Search()">查詢</el-button>
            <el-button  type="primary" @click="createInfor()"> 新建</el-button>
            <el-button  type="danger" round @click="batchDelete()"> 批量刪除</el-button>

          </el-col>
        </el-row>
      </div>

      <!--引用表格-->
      <el-table
        ref="singleTable" border
        :row-key="getRowKeys"
        stripe
        :height=(this.$store.state.bodyHeight-150)
        :reserve-selection="true"
        :data="tableData.lineItems.items"
        @selection-change="handleCurrentChange"
        style="width: 100%">
        <!--多選  prop要填唯一標(biāo)識(shí)-->
        <el-table-column label="選擇" :reserve-selection="true" prop="uuid" width="32px" type="selection">
        </el-table-column>
        <!--循環(huán)輸出表頭-->
        <el-table-column v-if="key!='id'" :label="value" :render-header="labelHeadFit"
                         v-for="(value, key) in tableData.table.header"
                         :key="value">
          <!--循環(huán)輸出對(duì)應(yīng)value-->
          <template slot-scope="scope">
            <span>{{scope.row[key]}}</span>
          </template>
        </el-table-column>
        <!--定義操作功能-->
        <el-table-column width="150px" label="操作">
          <template slot-scope="scope">
                        <span>
                          <el-button type="primary " size="mini" plain @click="editline(scope.row)">修改</el-button>
                          <el-button type="danger " size="mini" plain @click="deleteline(scope.row)">刪除</el-button>
                            </span>
          </template>
        </el-table-column>
      </el-table>
    </div>


    <!--分頁器-->
    <el-pagination
      @current-change="pageChange" v-if="tableData.isShow"
      :current-page="tableData.pageIndex"
      :page-size=tableData.fenye.pageSize
      layout="total, prev, pager, next, jumper"
      :total=tableData.lineItems.totalCount>
    </el-pagination>
    <!--新建條目的彈框-->
    <el-dialog title="信息" :visible.sync="tableData.dialogTableVisible">
      <el-form :model="form" class="inputWidth" ref="form">
        <el-form-item label="姓名" :label-width="formLabelWidth" prop="name"
                      :rules="[
      { required: true, message: '姓名不能為空',trigger: 'blur' },
    ]">
          <el-input v-model="form.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="性別" :label-width="formLabelWidth" prop="sex"
                      :rules="[
      { required: true, message: '請(qǐng)選擇性別',trigger: 'change' },
    ]">
          <el-select v-model="form.sex" placeholder="請(qǐng)選擇性別">
            <el-option label="男" value="男"></el-option>
            <el-option label="女" value="女"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="年齡" :label-width="formLabelWidth" prop="age"
                      :rules="[
      { required: true, message: '年齡不能為空'},
      { type: 'number', message: '年齡必須為數(shù)字值'}
    ]">
          <el-input type="age" v-model.number="form.age" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="tableData.dialogTableVisible = false">取 消</el-button>
        <el-button type="primary" @click="submit('form')">確 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
  //生成uuid唯一標(biāo)識(shí),可以不引用
  import UUID from 'node-uuid';

  export default {
    //接收父組件傳來的數(shù)據(jù)
    props: {
      tableData: Object,
    },
    data() {
      return {
        //控制label的寬度
        formLabelWidth: '80px',
        //記錄是修改還是新建
        type: "",
        form: {
          //唯一標(biāo)識(shí)
          uuid: "",
          name: '',
          sex: '',
          age: '',
        },
        // 獲取row的key值
        getRowKeys(row) {
          return row.uuid;
        },
        //存放分頁選中條目,回顯用
        selectedData: [],
        //存放選中條目,做傳參用
        templateRadio: [],
      }
    },
    mounted() {
    },
    methods: {
      //確定選中
      handleCurrentChange(rows) {
        console.log(rows);
        //將選中賦值到回顯和傳參數(shù)組
        this.templateRadio = rows;
        this.selectedData = [];
        if (rows) {
          rows.forEach(row => {
            if (row) {
              this.selectedData.push(row.uuid);
            }
          });
        }
      },
      //表頭自適應(yīng)
      labelHeadFit(h, {column, index}) {
        let l = column.label.length
        let f = 16 //每個(gè)字大小,其實(shí)是每個(gè)字的比例值,大概會(huì)比字體大小差不多大一點(diǎn),
        column.minWidth = f * l //字大小乘個(gè)數(shù)即長度 ,注意不要加px像素,這里minWidth只是一個(gè)比例值,不是真正的長度
        //然后將列標(biāo)題放在一個(gè)div塊中,注意塊的寬度一定要100%,否則表格顯示不完全
        return h('div', {class: 'table-head', style: {width: '100%'}}, [column.label])
      },
      //行項(xiàng)目分頁
      pageChange(val) {
        //將頁碼傳回父組件
        this.$emit("pageChange", val);
      },
      //新建行項(xiàng)目
      createInfor() {
        //生成uuid
        this.form.uuid = UUID.v1();
        //打開新建彈窗
        this.tableData.dialogTableVisible = true;
        //標(biāo)識(shí)為新建
        this.type = "createInfor"
      },
      //修改行項(xiàng)目
      editline(details) {
        //賦值詳情做展示用
        this.form = details
        this.tableData.dialogTableVisible = true;
        //標(biāo)識(shí)為修改
        this.type = "editline"
      },
      //刪除有行項(xiàng)目
      deleteline(details) {
        this.$emit("deleteline", details);
      },
      //批量刪除
      batchDelete(){
        this.$emit("batchDelete", this.templateRadio);
      },
      //查詢
      Search() {
        //將查詢的value傳回
        this.$emit("Search",this.tableData.search);
      },
      //提交時(shí)統(tǒng)一分發(fā)
      submit(formName) {
        console.log(formName, this.form)
        this.$refs[formName].validate((valid) => {
          if (valid) {
            switch (this.type) {
              //修改行項(xiàng)目
              case "editline":
                this.$emit("editline", this.form);
                break;
              //創(chuàng)建行項(xiàng)目
              case "createInfor":
                this.$emit("createInfor", this.form);
                break;
            }
          } else {
            console.log('error submit!!');
            return false;
          }
        });

      }
    }
  }
</script>


完整插件git地址,有幫助到你,就給我個(gè)星星喲~~
https://github.com/zccone/-plug-in-checkBoxTable

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 幾年前,命運(yùn)把我和西藏緊緊聯(lián)系在一起。當(dāng)?shù)谝淮我灾魅宋痰淖藨B(tài)走進(jìn)雪域高原這片神奇土地的時(shí)候,高原純美的風(fēng)景和生活在...
    觸動(dòng)的心靈閱讀 1,683評(píng)論 0 4
  • 飲酒 魏晉 · 陶淵明 結(jié)廬在人境,而無車馬喧。 問君何能爾?心遠(yuǎn)地自偏。 采菊東籬下,悠然見南山。 山氣日夕佳,...
    SeanQD閱讀 422評(píng)論 0 0
  • 莫嗟歲月太匆匆,喜看花蕊迎新春。 漫漫征途豈迷向,滔滔鄱水總流東。 坎坷難把初心改,名利焉將傲骨融。 攜手激情更奮...
    逸塵居士閱讀 625評(píng)論 0 0

友情鏈接更多精彩內(nèi)容