vue + element UI <table>表格的常見的案例

一.table組件的方法,事件

二.常用的事件,屬性

(一).屬性
1.多選框(type = "selection") 需要實現(xiàn)勾選的功能
在<el-table> 內(nèi)加入<el-table-column type="selection" width="55"></el-table-column>

2. :data="tableData" 是table的數(shù)據(jù)綁定

<el-table :data="tableData">
 
export default {   
    data() {
        return{
            tableData: [],
        }
    }
}

3.formatter 用來格式化內(nèi)容

對table的值進(jìn)行處理。Function(row, column, cellValue, index){}

A.使用formatter需要注意以下幾點:
①無論formatter出何種形式,格式化出的DOM一定都是被包含在默認(rèn)的div標(biāo)簽內(nèi)
②在寫formatter函數(shù)時要保證有值返回,否則單元格沒有內(nèi)容可展示,所以if的時候別忘了else
③formatter函數(shù)不會作用在列屬性checkbox為true的單元格上,checkbox列是組件預(yù)留的。

<template>
    <el-table :data="tableData3"  ref="multipleTable">
        <el-table-column type="selection" width="55" ></el-table-column>
        <el-table-column type="index" label="序號" width="60"></el-table-column>
        <el-table-column prop="sex" label="性別" width="100" :formatter="formatSex"></el-table-column>
        <el-table-column prop="date" label="日期"></el-table-column>
        <el-table-column prop="name" label="姓名"></el-table-column>
         <el-table-column prop="IsAudit"  :formatter="formatterColumn" label="審核狀態(tài)" ></el-table-column>
        <el-table-column prop="address" label="地址"></el-table-column>
    </el-table>
</template>
<script>
export default {   
    data() {
        return {
            tableData3: [{
                id:'1',
                date: '2016-05-03',
                name: '王小虎',
                address: '上海市普陀區(qū)金沙江路 1518 弄',
                IsAudit:0,
                sex:'1'
            }, {
                id:'2',
                date: '2016-05-02',
                name: '王小虎',
                address: '上海市普陀區(qū)金沙江路 1518 弄',
                IsAudit:1,
                sex:'0'
            }, {
                id:'3',
                date: '2016-05-02',
                name: '王小虎',
                address: '上海市普陀區(qū)金沙江路 1518 弄',
                IsAudit:10,
                sex:'-1'
            }]
        }
    },
    mounted() {
    },
    methods: {
        formatSex: function (row, column, cellValue, index) {
            return row.sex == 1 ? '男' : row.sex == 0 ? '女' : '未知';
        },
        //狀態(tài)改成漢字
        formatterColumn(row, column) {
            switch(row.IsAudit){
                case 0:
                    return '未通過';
                    break;
                case 1:
                    return '審核通過';
                    break;
                case 10:
                    return '待審核';
                    break;
                case 9:
                    return '草稿';
                    break;
                default:
                    return '未知';
            }
        }
    }
}
</script>
image.png

4.selectable (row, index) 是否可以選中

注意:僅對 type=selection 的列有效,類型為 Function,F(xiàn)unction 的返回值用來決定這一行的 CheckBox 是否可以勾選

使用:

<template>
    <el-table :data="tableData3"  ref="multipleTable" @row-click="handleCurrentChange">
        <el-table-column type="selection" width="55"  :selectable="selectable"></el-table-column>
    </el-table>
</template>
<script>
export default {   
    methods: {
        selectable(row, index){
            if(index === 1){
                return true;
            }else{
                return false;
            }
        }
    }
}
</script>

只有第二條是可以選中 其他不能


image.png

(二).方法
1.row-click 點擊行事件
<el-table @row-click="handleRowChange">
handleRowChange(row, event, column){ row此行的數(shù)據(jù) }
2.selection-change 獲取選中的所有值
<el-table @selection-change="selectionRowsChange">
selectionRowsChange(val){ val 選中的值}


image.png

1.table tr 點擊 復(fù)選框選中 再次點擊 復(fù)選框取消選中

①設(shè)置一個全局函數(shù)

exports.install = function (Vue, options) {  
    //刪除數(shù)組 指定的元素  
    Vue.prototype.removeByValue=function(arr, val){  
        for(var i=0; i<arr.length; i++) {  
            if(arr[i] == val) {  
                arr.splice(i, 1);  
                break;  
            }  
        }  
    };  
};  

②tableUser.vue

<!--用戶名 增刪改 基本操作-->
<template>
    <section>
        <!--工具條-->
        <el-col :span="24" class="el-table_headtoolbar" style="padding-bottom: 0px;">
            <el-form :inline="true" :model="filters" class="userform" label-width="50px">
                <el-form-item label="姓名"  prop="name">
                    <el-input v-model="filters.name" placeholder="姓名"  prefix-icon="el-icon-search"></el-input>
                </el-form-item>
                <el-form-item label="性別" prop="sex">
                    <el-select v-model="filters.sex" filterable placeholder="請選擇" prop="sex">
                        <el-option v-for="item in sexOptions" :key="item.value"  :label="item.label" :value="item.value">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-dropdown split-button type="primary" @click="btnSearch" trigger="click">
                    檢索
                    <el-dropdown-menu slot="dropdown" class="lyzbtn-group" trigger="click">
                        <el-dropdown-item @click.native="btnReset">重置</el-dropdown-item>
                    </el-dropdown-menu>
                </el-dropdown>
                <el-dropdown split-button type="primary" @click="btnNew" trigger="click">
                    新增
                    <el-dropdown-menu slot="dropdown" trigger="click">
                        <el-dropdown-item  @click.native="btnEdit">編輯</el-dropdown-item>
                        <el-dropdown-item  @click.native="btnDelete">刪除</el-dropdown-item>
                    </el-dropdown-menu>
                </el-dropdown>
            </el-form>
        </el-col>
        <!--列表-->
        <el-table :data="users.slice((page-1)*pagesize,page*pagesize)"  highlight-current-row v-loading="listLoading"  style="width: 100%;"  @selection-change="selsUserChange" class="userTableJs" @row-click="handleRowChange"  ref="table">
            <el-table-column type="selection" width="55">
            </el-table-column>
            <el-table-column type="index" label="序號" width="60">
            </el-table-column>
            <el-table-column prop="name" label="姓名" width="120">
            </el-table-column>
            <el-table-column prop="sex" label="性別" width="100" :formatter="formatSex">
            </el-table-column>
            <el-table-column prop="age" label="年齡" width="100" >
            </el-table-column>
            <el-table-column prop="birth" label="生日" width="120">
            </el-table-column>
            <el-table-column prop="addr" label="地址" min-width="180">
            </el-table-column>
        </el-table>
        <!--工具條-->
        <el-col :span="24" class="el-table_footertoolbar">
            <el-pagination layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChange" @current-change="handleCurrentChange" :page-sizes="[10, 20, 50, 100]" :page-size="pagesize" :total="users.length" style="float:right;">
            </el-pagination>
        </el-col>
        <!--新增界面-->
        <el-dialog title="新增" :visible.sync="addFormVisible">
            <el-form :model="addForm" label-width="80px" :rules="addFormRules" ref="addForm">
                <el-form-item label="姓名" prop="name">
                    <el-input v-model="addForm.name" auto-complete="off"></el-input>
                </el-form-item>
                <el-form-item label="性別">
                    <el-radio-group v-model="addForm.sex">
                        <el-radio class="radio" :label="1">男</el-radio>
                        <el-radio class="radio" :label="0">女</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="年齡">
                    <el-input-number v-model="addForm.age" :min="0" :max="200"></el-input-number>
                </el-form-item>
                <el-form-item label="生日">
                    <el-date-picker type="date" placeholder="選擇日期" v-model="addForm.birth"></el-date-picker>
                </el-form-item>
                <el-form-item label="地址">
                    <el-input type="textarea" v-model="addForm.addr"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click.native="addFormVisible = false">取消</el-button>
                <el-button type="primary" @click.native="addSubmit" :loading="addLoading">提交</el-button>
            </div>
        </el-dialog>
        <!--編輯界面-->
        <el-dialog title="編輯" :visible.sync="editFormVisible">
            <el-form :model="editForm" label-width="80px" :rules="editFormRules" ref="editForm">
                <el-form-item label="姓名" prop="name">
                    <el-input v-model="editForm.name" auto-complete="off"></el-input>
                </el-form-item>
                <el-form-item label="性別">
                    <el-radio-group v-model="editForm.sex">
                        <el-radio class="radio" :label="1">男</el-radio>
                        <el-radio class="radio" :label="0">女</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="年齡">
                    <el-input-number v-model="editForm.age" :min="0" :max="200"></el-input-number>
                </el-form-item>
                <el-form-item label="生日">
                    <el-date-picker type="date" placeholder="選擇日期" v-model="editForm.birth"></el-date-picker>
                </el-form-item>
                <el-form-item label="地址">
                    <el-input type="textarea" v-model="editForm.addr"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click.native="editFormVisible = false">取消</el-button>
                <el-button type="primary" @click.native="editSubmit" :loading="editLoading">提交</el-button>
            </div>
        </el-dialog>
    </section>
</template>
<script>
import util from '@/utils/index'//日期的操作
import { getUserListPage,batchRemoveUser,addUser,editUser} from '@/assets/api/api';//接口
export default {
    data() {
        return {
            filters: {
                name: ''
            },
            //性別
            sexOptions:[
                {value: '1',label: '男'}, 
                {value: '0',label: '女'}
            ],
            users: [],//表格數(shù)據(jù) 
            page: 1,//當(dāng)前頁數(shù)
            pagesize:10,//一頁顯示幾條
            listLoading: false,
            sels: [],//列表選中列
            total: 0,
            editFormVisible: false,//編輯界面是否顯示
            editLoading: false,
            editFormRules: {
                name: [{ required: true, message: '請輸入姓名', trigger: 'blur' }],
                birth: [{ type: 'date', required: true, message: '日期必須填寫', trigger: 'change' }]
            },
            //編輯界面數(shù)據(jù)
            editForm: {
                id:undefined,
                name: '',
                sex:-1,
                age: 0,
                birth:new Date(),
                addr: ''
            },
 
            addFormVisible: false,//新增界面是否顯示
            addLoading: false,
            addFormRules: {
                name: [{ required: true, message: '請輸入姓名', trigger: 'blur' },],
                birth: [{ type: 'date', required: true, message: '日期必須填寫', trigger: 'change' }]
            },
            //新增界面數(shù)據(jù)
            addForm: {
                name: '',
                sex: -1,
                age: 0,
                birth: new Date(),
                addr: ''
            },
            arrID:[],
 
        }
    },
    methods: {
        //性別顯示轉(zhuǎn)換
        formatSex: function (row, column) {
            return row.sex == 1 ? '男' : row.sex == 0 ? '女' : '未知';
        },
        //初始頁page、初始每頁數(shù)據(jù)數(shù)pagesize和數(shù)據(jù)data
        handleSizeChange(size){
            this.pagesize = size;
        },
        handleCurrentChange(val) {
            this.page = val;
            this.getUsers();
        },
        handleRowChange(row, event, column){
            var same=false;
            if(this.arrID.length > 0){
                for(var i=0; i<this.arrID.length ;i++){
                    if(this.arrID[i]==row.id){
                        same=true;
                        this.removeByValue(this.arrID, row.id);
                        break;
                    }
                }
                if(same==true){
                    this.$refs.table.toggleRowSelection(row,false);
                }else{
                    this.$refs.table.toggleRowSelection(row,true);
                    this.arrID.push(row.id);
                }
            }else{
                this.$refs.table.toggleRowSelection(row,true);
                this.arrID.push(row.id);
            }
        },
        //獲取用戶列表
        getUsers() {
            let para = {
                page: this.page,
                name: this.filters.name,
                sex: this.filters.sex
 
            };
            this.listLoading = true;
            getUserListPage(para).then((res) => {
                this.users = res.data.users;
                this.total = res.data.total;
                this.listLoading = false;
                
            });
        },
        //檢索
        btnSearch(){
            console.log('檢索')
            var searchParams = { name: this.filters.name, sex: this.filters.sex };
                //searchUser(searchParams).then(data => {
                
                //});
        },
        //重置
        btnReset(){
            this.resetForm(".userform");
        },
        //新增
        btnNew(){
            this.addFormVisible = true;
        },
        //編輯
        btnEdit(){
            var ids = this.sels.map(item => item.id);
            if(ids =='' || ids.length >1){
                this.$alert('請選擇一條要編輯的記錄', '提示', {
                    dangerouslyUseHTMLString: true
                });
            }else{
                const obj={};
                obj.id=this.sels.map(item => item.id).toString();
                obj.name=this.sels.map(item => item.name).toString();
                console.log(this.sels.map(item => item.sex).toString())
                if(this.sels.map(item => item.sex).toString() == 1){
                    obj.sex=1;
                }else if(this.sels.map(item => item.sex).toString() == 0){
                    obj.sex=0;
                }else{
                    obj.sex=-1;
                }
                obj.age=this.sels.map(item => item.age).toString();
                obj.birth=this.sels.map(item => item.birth).toString();
                obj.addr=this.sels.map(item => item.addr).toString();
                this.editFormVisible = true;
                this.editForm = Object.assign({},obj);
            }
 
        },
        //刪除
        btnDelete(){
            var ids = this.sels.map(item => item.id).toString();
            if(ids ==''){
                this.$alert('請選擇要刪除的記錄', '提示', {
                    dangerouslyUseHTMLString: true
                });
            }else{
                this.$confirm('確認(rèn)刪除選中記錄嗎?', '提示', {
                    type: 'warning'
                }).then(() => {
                    this.listLoading = true;
                    //NProgress.start();
                    let para = { ids: ids };
                    batchRemoveUser(para).then((res) => {
                        this.listLoading = false;
                        //NProgress.done();
                        this.$message({
                            message: '刪除成功',
                            type: 'success'
                        });
                        this.getUsers();
                    });
                }).catch(() => {
 
                });
            }
        },
        //編輯
        editSubmit: function () {
            this.$refs.editForm.validate((valid) => {
                if (valid) {
                    this.$confirm('確認(rèn)提交嗎?', '提示', {}).then(() => {
                        this.editLoading = true;
                        //NProgress.start();
                        let para = Object.assign({}, this.editForm);
                        para.birth = (!para.birth || para.birth == '') ? '' : util.formatDate.format(new Date(para.birth), 'yyyy-MM-dd');
                        editUser(para).then((res) => {
                            this.editLoading = false;
                            //NProgress.done();
                            this.$message({
                                message: '提交成功',
                                type: 'success'
                            });
                            this.$refs['editForm'].resetFields();
                            this.editFormVisible = false;
                            this.getUsers();
                        });
                    });
                }
            });
        },
        //新增
        addSubmit: function () {
            this.$refs.addForm.validate((valid) => {
                if (valid) {
                    this.$confirm('確認(rèn)提交嗎?', '提示', {}).then(() => {
                        this.addLoading = true;
                        //NProgress.start();
                        let para = Object.assign({}, this.addForm);
                        para.birth = (!para.birth || para.birth == '') ? '' : util.formatDate.format(new Date(para.birth), 'yyyy-MM-dd');
                        addUser(para).then((res) => {
                            this.addLoading = false;
                            //NProgress.done();
                            this.$message({
                                message: '提交成功',
                                type: 'success'
                            });
                            this.$refs['addForm'].resetFields();
                            this.addFormVisible = false;
                            this.getUsers();
                        });
                    });
                }
            });
        },
        selsUserChange(sels) {
            this.sels = sels;
            if(sels.length>0){
                var valId=[];
                for(var i=0;i<sels.length;i++){
                    var arrIDsame=false;
                    valId.push(sels[i].id);
                }
                this.arrID=valId;
            }
        }
    },
    mounted() {
        this.getUsers();
        
    }
}
</script>

3.table行內(nèi)編輯
vue slot的scope傳遞,要表述的意思組件中slot這個插槽上可以賦值各種屬性,在調(diào)用組件的頁面中可以使用<template slot-scope="props"> 來獲取插槽上的屬性值,獲取到的值是一個對象。
(1).一行一行編輯

<template>
    <el-table :data="tableData" style="width: 100%">
        <el-table-column label="日期" width="180">
            <template slot-scope="scope">
                <span>{{scope.row.date}}</span>
            </template>
        </el-table-column>
        <el-table-column prop="name" label="姓名">
            <template slot-scope="scope">
                <span>{{scope.row.name}}</span>
            </template>
        </el-table-column>
        <el-table-column prop="address" label="地址">
            <template slot-scope="scope">
                <template v-if="scope.row.edit">
                    <el-input class="edit-input" size="small" v-model="scope.row.address"></el-input>
                </template>
                <span v-else>{{ scope.row.address }}</span>
            </template>
        </el-table-column>
        <el-table-column label="操作">
            <template slot-scope="scope">
                <el-button v-if="scope.row.edit" type="success" @click="confirmEdit(scope.$index, scope.row)" size="small" icon="el-icon-circle-check-outline">保存</el-button>
                <el-button v-else type="primary" @click='scope.row.edit=!scope.row.edit' size="small" icon="el-icon-edit">編輯</el-button>
            </template>
        </el-table-column>
    </el-table>
</template>
 
<script>
  export default {
    data() {
      return {
        tableData: [{
            id:'1',
            date: '2016-05-02',
            name: '王小虎',
            address: '上海市普陀區(qū)金沙江路 1518 弄',
            edit:false
        }, {
            id:'2',
            date: '2016-05-04',
            name: '王小虎',
            address: '上海市普陀區(qū)金沙江路 1517 弄',
            edit:false
        }, {
            id:'3',
            date: '2016-05-01',
            name: '王小虎',
            address: '上海市普陀區(qū)金沙江路 1519 弄',
            edit:false
        }, {
            id:'4',
            date: '2016-05-03',
            name: '王小虎',
            address: '上海市普陀區(qū)金沙江路 1516 弄',
            edit:false
        }]
      }
    },
    methods: {
        confirmEdit(index,row){
            row.edit = false;
            this.$message({
                message: '該地址已經(jīng)成功修改',
                type: 'success'
            })
        }
    }
  }
</script>
image.png

(2).table批量編輯列字段

<template>
    <section>
        <!--工具條-->
        <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
            <el-button v-if="editOk"  type="success" @click="btnOk" size="small" icon="el-icon-circle-check-outline">保存</el-button>
            <el-button v-else="editOk" type="primary"  @click="btnEdit" size="small" icon="el-icon-edit">編輯</el-button>
        </el-col>
        <el-table :data="tableData" style="width: 100%">
            <el-table-column label="日期" width="180">
                <template slot-scope="scope">
                    <span>{{scope.row.date}}</span>
                </template>
            </el-table-column>
            <el-table-column prop="name" label="姓名">
                <template slot-scope="scope">
                    <span>{{scope.row.name}}</span>
                </template>
            </el-table-column>
            <el-table-column prop="address" label="地址">
                <template slot-scope="scope">
                    <template  v-if="editOk">
                        <el-input class="edit-input" size="small" v-model="scope.row.address"></el-input>
                    </template>
                    <span v-else>{{ scope.row.address }}</span>
                </template>
            </el-table-column>
        </el-table>
    </section>
</template>
<script>
  export default {
    data() {
      return {
        tableData: [{
            id:'1',
            date: '2016-05-02',
            name: '王小虎',
            address: '上海市普陀區(qū)金沙江路 1518 弄',
        }, {
            id:'2',
            date: '2016-05-04',
            name: '王小虎',
            address: '上海市普陀區(qū)金沙江路 1517 弄',
        }, {
            id:'3',
            date: '2016-05-01',
            name: '王小虎',
            address: '上海市普陀區(qū)金沙江路 1519 弄',
        }, {
            id:'4',
            date: '2016-05-03',
            name: '王小虎',
            address: '上海市普陀區(qū)金沙江路 1516 弄',
        }],
        editOk:false
      }
    },
    methods: {
        btnEdit(){
             this.editOk=true;
        },
        btnOk(){
            this.editOk=false;
        }
    }
  }
</script>
image.png
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容