公司平台利用vue+elementui搭建前端页面,由于本人第一次使用vue也遇到了很多坑,由于我要实现的效果以下图所示html
实现这种单选框,只能选择一个,但element-ui展现的是多选框,checkbox本身也能够写,但不想写,仍是想用element-ui实现表格单选,因而就用了element-ui中的方法实现了,贴代码:前端
methods: { select (selection, row) { console.log(selection.length); console.log( Object.prototype.toString.call(selection[0]) === '[object Object]' ); this.$refs.multipleTable.clearSelection(); if (selection.length === 0) { // 判断selection是否有值存在 return; }; console.log('点击', selection, row); this.$refs.multipleTable.toggleRowSelection(row, true); } }
其中select对应的事件名是table的select事件,我利用selection参数判断参数是否选中,selection选中 (2) [{…}, {…}, __ob__: Observer] ,未选中是: [ __ob__: Observer] ,__ob__: Observer是observe 工厂函数 也是实现数据响应式, 原本想用Object.prototype.toString.call(selection[0]) === '[object Object]' 这个判断的,因本人粗心,将'[object Object]'写成了'[Object Object]'致使判断不对,最后改为了数组的长度判断,正常selection选中 (2) [{…}, {…}, __ob__: Observer] 里面应该有一个对象的,由于单选,没有将上个对象清除因此致使如今选中有两个对象,可是没有关系,由于咱们用row, table在选择是会触发select事件,先将this.$refs.multipleTable.clearSelection();清除掉表格的选中状态,后面开始判断若没有选中checkbox则return,不然利用row,this.$refs.multipleTable.toggleRowSelection(row, true);选中当前行,我在作的时候让表格默认选中第一行;代码以下:vue
1 methods: { 2 getManage (data = {}) { // 获取列表 3 this.$nextTick(() => { 4 manageList(data).then(res => { 5 this.manageList = res.storages || []; 6 console.log(this.manageList); 7 if (this.manageList.length === 0) { return; }; 8 setTimeout(() => { 9 this.$refs.multipleTable.toggleRowSelection(this.manageList[0], true);11 }, 0); 12 }); 13 }); 14 }, 15 mounted () { 16 this.getManage(); 17 },
manageList(data)是我封装的请求列表的函数,因此这个不用管,this.manageList = res.storages || [];这个是判断我是否请求到数据,if (this.manageList.length === 0) { return; }; 若是没有数据表格就是空的,返回,其实这两步我主要是针对搜索的,由于搜索不对会没有数据,最主要的就是下面一步
setTimeout(() => {this.$refs.multipleTable.toggleRowSelection(this.manageList[0], true);}, 0); 若是有数据的状况下,就获取表格的第一行数据,就能够默认选中第一行,若是不使用settimeout是不会选中的,由于vue是异步更新,个人理解是由于vue是异步更新,不添加setTimeout,咱们里面的代码是同步的,在数据变化,dom更新以前默认选中第一行已经执行,但dom尚未更新渲染,等到$nextTick完成页面更新渲染,咱们的选中行代码已经执行完毕,加上settimeout一样是异步操做,同时也能获取到dom数据变化以后dom更新,对于更深的还有待研究