公司平台利用vue+elementui搭建前端頁面,因為本人第一次使用vue也遇到了不少坑,因為我要實現的效果如下圖所示
實現這種單選框,只能選擇一個,但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);選中當前行,我在做的時候讓表格默認選中第一行;代碼如下:
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更新,對於更深的還有待研究