ag-grid動態生成表頭及綁定表數據


ag-grid動態加載表數據

  優勢:靈活度高,代碼復用性強

實現步驟:

1.  安裝 ag-grid-vue 組件,

        在vue項目中,運行如下命令即可安裝

        npm install --save ag-grid-community ag-grid-vue vue-property-decorator@^8.0.0

      安裝完成后,在 package.json 文件中可以看到如下組件,說明已經安裝成功

   

     在后續運行項目過程中,如果提示要安裝  enterprise 組件,根據控制台提示的命令安裝即可。

    npm install --save ag-grid-enterprise

2. 在vue頁面中引入組件 

import "ag-grid-community/dist/styles/ag-grid.css";
import "ag-grid-community/dist/styles/ag-theme-balham.css"
import {AgGridVue} from "ag-grid-vue"
import "ag-grid-enterprise"  //關鍵依賴:引入之后組件才會生效

 其中:ag-grid-enterprise 是非常關鍵的依賴,一定要導入,aggrid組件才會生效。

3. 在 components 方法中注冊 AgGridVue

   

4. 搭建aggrid框架

      <!--右側內容欄(動態表格)-->
      <div class="commendContent" id="ag-gridStyle">
        <ag-grid-vue
                class="table ag-theme-balham"
                v-show="isSee"
                id="myGrid"
                :columnDefs="columnDefs"
                :rowData="rowData"
                :sideBar="sideBar"
                :enableColResize="true"
                row-selection="multiple"
                @selection-changed="onSelectionChanged"
                @gridReady="onGridReady"
                :tooltipShowDelay="tooltipShowDelay"
                :localeText="localeText"
                :height="tableMaxHeight"
        >
        </ag-grid-vue>
      </div>

  框架搭建完成之后,一定要指定table的高度,否則列表不會展示數據

  

  5. 定義aggrid相關變量及完成漢化

      //ag-grid相關
      domLayout:null,  //高度自適應,根據獲取到的數據條數自適應高    度,加載速度慢,頁面卡頓,不推薦使用
      tooltipShowDelay: [],  //鼠標懸浮在單元格上,顯示全名
      gridOptions: {},
      gridApi: {},
      columnApi: [],
      //定義ag-grid列
      columnDefs: [],
      //ag-grid需要顯示的數據
      rowData: [],
      //ag-grid列表右側的過濾器
      sideBar: [],
      //存放多選框選中的數據
      selectRows: [],
      // 當輸入sql錯誤和結果集為0的時候不顯示aggrid表格
      isSee: true,
      globalDropDownBox: false, //移入顯示下拉框
      globalDropTop: 0,
      globalDropLeft: 0,
      timeOut: setTimeout,
      modelDetailRelation: [], // 存放模型詳細關聯表
      countData:'',
      selectedData:0,
      //ag-grid漢化
      localeText:{
        // for filter panel
        page: '頁',
        more: '更多',
        to: '到',
        /* of: 'daOf', */
        next: '下一頁',
        last: '最后',
        first: '第一',
        previous: '以前的',
        loadingOoo: '加載中...',
        // Row:"行",
        // 'Row Groups':"行分組",
        // for set filter
        selectAll: '全部選擇',
        searchOoo: '搜索...',
        blanks: '空',
        Column:"列",
        labels:"標簽",
        // for number filter and text filter
        filterOoo: '過濾',
        applyFilter: '過濾中...',
        equals: '等於',
        notEqual: '不等於',
        // for number filter
        lessThan: '少於',
        greaterThan: '多於',
        lessThanOrEqual: '小於等於',
        greaterThanOrEqual: '大於等於',
        inRange: '在范圍內',
        // for text filter
        contains: '包含',
        notContains: '不包含',
        startsWith: '開始',
        endsWith: '結束',
        // filter conditions
        andCondition: '並且',
        orCondition: '或者',
        // the header of the default group column
        // group: '分組',
        // tool panel
        columns: '列',
        filters: '過濾器',
        rowGroupColumns: '行列組',
        // rowGroupColumnsEmptyMessage: '行列組為空',
        valueColumns: '列值',
        pivotMode: '透視模式',
        // groups: '分組',
        values: '值',
        // pivots: '中心點',
        valueColumnsEmptyMessage: '列值為空',
        // pivotColumnsEmptyMessage: '中心點為空',
        toolPanelButton: '工具按鈕',
        // other
        noRowsToShow: '暫時沒有要展示的數據',
        // enterprise menu
        pinColumn: '列位置調整',
        valueAggregation: '聚合值',
        autosizeThiscolumn: '自動調整此列大小',
        autosizeAllColumns: '自動調整所有列的大小',
        groupBy: '分組',
        ungroupBy: '取消分組',
        resetColumns: '重置列',
        expandAll: '展開所有',
        collapseAll: '關閉所有',
        toolPanel: '工具',
        export: '導出',
        csvExport: 'CSV 導出',
        excelExport: 'Excel 導出(.xlsx)',
        excelXmlExport: 'Excel 導出(.xml)',
        // enterprise menu pinning
        PinColumn:"固定",
        pinLeft: '居左',
        pinRight: '居右',
        noPin: '默認',
        // enterprise menu aggregation and status bar
        sum: '合計',
        min: '最小值',
        max: '最大值',
        /* none: 'laNone', */
        count: '計數',
        average: '平均值',
        avg : '平均值',
        // standard menu
        copy: '復制',
        copyWithHeaders: '攜表頭復制',
        ctrlC: 'ctrl-C',
        paste: '粘貼',
        ctrlV: 'ctrl-V'
      },             

6. 開啟列表右側的工具面板

      this.gridOptions = {}
      this.sideBar = true;  //開啟右側面板的關鍵代碼
      this.domLayout = 'autoHeight';  //高度自適應

7. aggrid創建完后之后要執行的事件

    onGridReady(params) {
      // 獲取gridApi
      this.gridApi = params.api;
      this.columnApi = params.columnApi;
      // 這時就可以通過gridApi調用ag-grid的傳統方法了
      this.gridApi.sizeColumnsToFit();
      //默認隱藏右側欄
      this.gridApi.closeToolPanel();
      this.gridApi.getDisplayedRowCount();

    }

完整的aggrid動態加載實例:

<template>
    <div>
        <el-card class="box-card" style="margin-left: 14px;width: 100%;float: right;">
            <div>
                <el-button
                        class="buttonStyle"
                        type="primary"
                        plain
                        @click="submitForm()"
                >
                    提交審核
                </el-button>
                <ag-grid-vue
                        class="table ag-theme-balham"
                        v-show="isSee"
                        id="myGrid"
                        :columnDefs="columnDefs"
                        :rowData="rowData"
                        :sideBar="sideBar"
                        :enableColResize="true"
                        row-selection="multiple"
                        :localeText="localeText"
                >
                </ag-grid-vue>
            </div>
            <!--分頁組件-->
            <div class="block"
                 style="float: right;margin-right: 15px;margin-top: 10px;">
                <el-pagination
                        @size-change="handleSizeChange($event)"
                        @current-change="handleCurrentChange($event)"
                        :current-page="page.current"
                        :page-sizes="[10, 15, 20]"
                        :page-size="page.size"
                        layout="total, sizes, prev, pager, next, jumper"
                        :total="this.page.total">
                </el-pagination>
            </div>
        </el-card>
    </div>
</template>

<script>
import "ag-grid-community/dist/styles/ag-grid.css";
import "ag-grid-community/dist/styles/ag-theme-balham.css";
import { AgGridVue } from "ag-grid-vue"
import "ag-grid-enterprise"  //關鍵依賴:引入之后組件才會生效
import {loadContentData} from "@/api/warning/warningdata";

export default {
    name: "show",
    components:{
        AgGridVue,
    },
    data (){
        return{
            gridOptions: {},
            gridApi: {},
            columnApi: [],
            //定義ag-grid列
            columnDefs: [],
            //ag-grid需要顯示的數據
            rowData: [],
            //ag-grid列表右側的過濾器
            sideBar: [],
            //存放多選框選中的數據
            selectRows: [],
            // 當輸入sql錯誤和結果集為0的時候不顯示aggrid表格
            isSee: true,
            //ag-grid漢化
            localeText:{
                // for filter panel
                page: '頁',
                more: '更多',
                to: '到',
                /* of: 'daOf', */
                next: '下一頁',
                last: '最后',
                first: '第一',
                previous: '以前的',
                loadingOoo: '加載中...',
                // Row:"行",
                // 'Row Groups':"行分組",
                // for set filter
                selectAll: '全部選擇',
                searchOoo: '搜索...',
                blanks: '空',
                Column:"列",
                labels:"標簽",
                // for number filter and text filter
                filterOoo: '過濾',
                applyFilter: '過濾中...',
                equals: '等於',
                notEqual: '不等於',
                // for number filter
                lessThan: '少於',
                greaterThan: '多於',
                lessThanOrEqual: '小於等於',
                greaterThanOrEqual: '大於等於',
                inRange: '在范圍內',
                // for text filter
                contains: '包含',
                notContains: '不包含',
                startsWith: '開始',
                endsWith: '結束',
                // filter conditions
                andCondition: '並且',
                orCondition: '或者',
                // the header of the default group column
                // group: '分組',
                // tool panel
                columns: '列',
                filters: '過濾器',
                rowGroupColumns: '行列組',
                // rowGroupColumnsEmptyMessage: '行列組為空',
                valueColumns: '列值',
                pivotMode: '透視模式',
                // groups: '分組',
                values: '值',
                // pivots: '中心點',
                valueColumnsEmptyMessage: '列值為空',
                // pivotColumnsEmptyMessage: '中心點為空',
                toolPanelButton: '工具按鈕',
                // other
                noRowsToShow: '沒有可以展示的數據',
                // enterprise menu
                pinColumn: '列位置調整',
                valueAggregation: '聚合值',
                autosizeThiscolumn: '自動調整此列大小',
                autosizeAllColumns: '自動調整所有列的大小',
                groupBy: '分組',
                ungroupBy: '取消分組',
                resetColumns: '重置列',
                expandAll: '展開所有',
                collapseAll: '關閉所有',
                toolPanel: '工具',
                export: '導出',
                csvExport: 'CSV 導出',
                excelExport: 'Excel 導出(.xlsx)',
                excelXmlExport: 'Excel 導出(.xml)',
                // enterprise menu pinning
                PinColumn:"固定",
                pinLeft: '居左',
                pinRight: '居右',
                noPin: '默認',
                // enterprise menu aggregation and status bar
                sum: '合計',
                min: '最小值',
                max: '最大值',
                /* none: 'laNone', */
                count: '計數',
                average: '平均值',
                avg : '平均值',
                // standard menu
                copy: '復制',
                copyWithHeaders: '攜表頭復制',
                ctrlC: 'ctrl-C',
                paste: '粘貼',
                ctrlV: 'ctrl-V'
            },
            //分頁相關(參數)
            page: {current: 1, size: 10, total: 0, records: []},
            pageQueryTree: {
                condition: {},
                pageNo: 1,
                pageSize:10,
                sortBy: 'asc',
                sortName: 'create_time',
                modelParamName: '',
            },
            beforeTableName: ''
        };
    },
    methods:{
        //獲取預警表數據,將返回的數據放在ag-grid-vue 組件上
        getData(tableName){
            this.pageQueryTree.condition.單位名稱 = tableName;
            this.pageQueryTree.condition.統一社會信用代碼 = '';
            loadContentData(this.pageQueryTree).then(resp =>{
                var jsonStr = JSON.stringify(resp.data);
                var items = resp.data.columnData
                this.columnDefs = []  //表頭
                for(let i in items){
                    //過濾掉pk主鍵
                    if ("PK主鍵" !== items[i].columnName){
                        if (1 == i){
                            var obj ={
                                headerName: items[i].columnName,
                                field: items[i].columnName,
                                filter: true,
                                //flex: 1,    該字段會影響列的寬度
                                editable: true,
                                checkboxSelection: true
                            };
                            this.columnDefs.push(obj);
                        }else {
                            var obj ={
                                headerName: items[i].columnName,
                                field: items[i].columnName,
                                filter: true,
                                //flex: 1,    該字段會影響列的寬度
                                editable: true,
                            };
                            this.columnDefs.push(obj);
                        }
                    }
                };
                //獲取表數據
                this.rowData = []
                for (var i = 0; i < resp.data.specifyData.records.length;i++){
                    //alert("返回數據的長度是:"+resp.data.specifyData.records.length)
                    var items = resp.data.specifyData.records[i];
                    if (items.狀態 === 0) {
                        items.狀態 = '待掛號'
                    } else if (items.狀態 === 1) {
                        items.狀態 = '掛號中'
                    } else if (items.狀態 === 2) {
                        items.狀態 = '預警待查'
                    } else { // 3
                        items.狀態 = '已銷號'
                    }
                    this.rowData.push(items);
                }
                //分頁的總條數
                this.page.total = resp.data.specifyData.total;
            })
            this.gridOptions = {}
            this.sideBar = true;   //這是ag-grid列表右側的篩選器,不能刪除
        },
        //獲取所選節點的列表
        submitForm(){

        }
    },
    mounted() {
        this.gridApi = this.gridOptions.api;
        this.columnApi = this.gridOptions.columnApi;
    }
}
</script>

<style scoped>
    .table {
        width: 600px;
        height: 520px;
    }
    #myGrid {
        flex: 1 1 0px;
        width: 100%;
    }
    .buttonStyle {
        background: #559ed4;
        width: 70px;
        height: 24px;
        padding: 4px;
        border-radius: 4px;
        position: relative;
        color: #ffffff;
        font-style: normal;
        font-family: "iconfont" !important;
        font-weight: normal !important;
        margin-right: 6px;
        margin-left: 970px;
        margin-bottom: 2px;
    }
</style>

 

 

 

   

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM