安装
npm install handsontable @handsontable/vue
引入
<template>
<HotTable :root="root" :data="tableValue" ref="testHot" :settings="hotSettings"></HotTable>
</template>
<script>
import HotTable from '@handsontable/vue';
export default {
components: { HotTable }
}
</script>
<style src="../node_modules/handsontable/dist/handsontable.full.css"></style>
属性及使用
以下内容有涉及到dom操作可以看我的另一篇文章dom操作
<script>
export default {
data() {
return {
hotSettings: {
rowHeaders: true,//行表头,可以使布尔值(行序号),可以使字符串(左侧行表头相同显示内容,可以解析html),也可以是数组(左侧行表头单独显示内容)。
minSpareCols: 2, //列留白
minSpareRows: 2,//行留白
minRows: 20, //最小行列
maxRows: 20000, //最大行列
currentRowClassName: 'currentRow', //为选中行添加类名,可以更改样式
currentColClassName: 'currentCol',//为选中列添加类名
autoWrapRow: true, //自动换行
manualColumnFreeze: true, //手动固定列
manualColumnMove: true, //手动移动列
manualRowMove: true, //手动移动行
manualColumnResize: true,//手工更改列距
manualRowResize: true,//手动更改行距
comments: true, //添加注释
customBorders: [], //添加边框
columnSorting: true, //排序
stretchH: "all", //根据宽度横向扩展,last:只扩展最后一列,none:默认不扩展
fillHandle: true, //选中拖拽复制 possible values: true, false, "horizontal", "vertical"
fixedColumnsLeft: 2,//固定左边列数
fixedRowsTop: 2,//固定上边列数
mergeCells: [
//合并
// {row: 1, col: 1, rowspan: 3, colspan: 3}, //指定合并,从(1,1)开始行3列3合并成一格
// {row: 3, col: 4, rowspan: 2, colspan: 2}
],
colHeaders: ['表头'],//自定义列表头or 布尔值
colWidths: ['列宽度'],//设置每一列的宽度
columns: [{ data: "字段名", type: "text"文本/"dropdown"下拉菜单/"date"日期, readOnly: true//只读 },],//添加每一列的数据类型和一些配置
cells: this.rowReadonly, //为单元格设置属性
afterRender: this.setRowColStyle //渲染完成后调用
}
}
},
methods:{
//设置表格的锁定函数,满足条件的变为readonly
rowReadonly(row, col, prop) {
var cellProperties = {};
if(col==0){//列数是1的
cellProperties.readOnly = true;
}
if(col==9 && row < 2){//第10列第3行的
cellProperties.readOnly = true;
}
if(row==9){//行数是10的
cellProperties.readOnly = true;
}
return cellProperties;
},
// 渲染结束后调用
setRowColStyle(){
const testHot = this.$refs.testHot.hotInstance;
let col = '';
let colname = ''
this.hotSettings.columns.some((item, index) => {//获取想要操作的字段col
if (item.data == "字段名") {
col = index;
colname = item.data
return true;
}
});
this.tableValue.forEach((item, row) => {
if (row >= 0 && colname == '字段名') {
try {//对该列数据操作的方法,这里举例把他替换为按钮
const cellele = testHot.getCell(row, col);
const cellmet = testHot.getCellMeta(row, col);
let btn = document.createElement("a");
cellele.style = "color: aquamarine !important;text-align: center;";
btn.textContent = "操作";//按钮文字设置
btn.style = "font-size:10px; border-bottom: 1px solid #2d8cf0";//按钮行内样式设置
btn.addEventListener("click", event => {});//点击事件的设置
// console.log(cellele);
cellele.innerHTML = ""; // 清空单元格子集
cellele.appendChild(btn); //添加按钮到单元格
} catch (e) {
console.log(e);
}
}
});
}
}
}
</script>
官方文档
https://handsontable.com/features