一、整个表格(表头加数据)动态变化:
1、效果:
点击表头,弹出选择框:
2、代码:
<template>
<div>
<!--<div v-show="true" class="menu1" style="width:10%;float:left">
<el-checkbox-group v-model="colOptions">
<el-checkbox v-for="item in colSelect" :key="item" :label="item" />
</el-checkbox-group>
</div>
<div style="width:70%">
<table highlight-current-row @header-contextmenu="contextmenu" style="width: 70%;float:right">
<tr>
<td
v-for="(item,index) in tableHeader"
v-if="colData[index].istrue"
width="180"
>{{item.label}}</td>
</tr>
<tr v-for="(item,index) in tableData">
<td>{{item.id}}</td>
</tr>
</table>-->
<el-table @header-contextmenu="contextmenu" :data="tableData" style="width: 100%">
<el-table-column
v-for="(item,index) in tableHeader"
v-if="colData[index].istrue"
:key="item.key"
show-overflow-tooltip
:label="item.label"
:prop="item.key"
>
</el-table-column>
</el-table>
<!--右键弹出的菜单内容-->
<!--动态计算菜单出现的位置-->
<div
v-show="menuVisible"
:style="{top:top+ "px",left:left+ "px"}"
class="menu1"
>
<el-checkbox-group v-model="colOptions">
<el-checkbox v-for="item in colSelect" :key="item" :label="item" />
</el-checkbox-group>
</div>
</div>
</template>
<script>
export default {
data() {
return {
//所有的列
tableHeader: [
{ label: "ID", key: "id" },
{ label: "编号", key: "num" },
{ label: "类型", key: "type" },
{ label: "价格", key: "price" },
{ label: "名称", key: "name" }
],
menuVisible: false, //右键菜单的显示与隐藏
top: 0, //右键菜单的位置
left: 0,
colOptions: ["id", "num", "type", "price", "name"], //多选框的选择项
colSelect: ["id", "num", "type", "price", "name"], //多选框已选择的内容,即表格中显示的列
tableData: [{ id: 1, num: "111", type: "aaa", price: 10, name: "vv" }],
// istrue属性存放列的状态
colData: [
{ title: "id", istrue: true },
{ title: "num", istrue: true },
{ title: "type", istrue: true },
{ title: "price", istrue: true },
{ title: "name", istrue: true }
]
};
},
watch: {
colOptions(newVal, oldVal) {
if (newVal) {
//如果有值发生变化,即多选框的已选项变化
var arr = this.colSelect.filter(i => newVal.indexOf(i) < 0); // 未选中
this.colData.filter(i => {
if (arr.indexOf(i.title) !== -1) {
i.istrue = false;
} else {
i.istrue = true;
}
});
}
}
},
methods: {
contextmenu(row, event) {
//先把菜单关闭,目的是第二次或者第n次右键鼠标的时候 它默认的是true
this.menuVisible = false;
// 显示菜单
this.menuVisible = true;
window.event.returnValue = false; //阻止浏览器自带的右键菜单弹出
//给整个document绑定click监听事件, 左键单击任何位置执行foo方法
document.addEventListener("click", this.foo);
//event对应的是鼠标事件,找到鼠标点击位置的坐标,给菜单定位
this.top = event.clientY;
this.left = event.clientX;
},
foo() {
this.menuVisible = false; //关闭菜单栏
document.removeEventListener("click", this.foo); //解绑click监听,很重要,具体原因可以看另外一篇博文
}
}
};
</script>
<style>
.menu1 {
position: fixed;
height: auto;
width: 231px;
border-radius: 3px;
border: 1px solid #999999;
background-color: #f4f4f4;
padding: 10px;
z-index: 1000;
}
.el-checkbox {
display: block;
height: 20px;
line-height: 20px;
padding: 0 5px;
margin-right: 0;
font-size: 12px;
border: 1px solid transparent;
}
.el-checkbox:hover {
border-radius: 3px;
border: 1px solid #999999;
}
</style>
二、