個人技術總結——Vxe-table


1、技術概述

Vxe-table是一個Vue的表格插件,我們項目需要實現填寫表格的功能,於是我就找到了這個插件。難點在於,我覺得這個插件的手冊寫得不是很好,很多地方要自己研究。

2、技術詳述

簡單來說,Vxe-table由三個部分組成,表格樣式,表格數據,表格方法。

表格樣式

表格樣式由參數來控制,表格要調用的方法也是寫在參數上的。

<div id="OuterEditableTable" class="container col-md-10 offset-md-1" style="margin: 50px auto;">
	<h2>{{this.$data.title}}</h2>
	<vxe-grid
	 v-if="ready"
	 border
	 keep-source
	 resizable
	 ref="xTable"
	 :columns="tableColumn"<!-- 表頭 -->
	 :data="tableData"<!-- 數據 -->
	 :edit-config="{trigger: 'click', mode: 'cell'}"<!-- 表格編輯事件,這樣代表單個表格點擊編輯 -->
	 :edit-rules="validRules"<!-- 表格校驗規則 -->
	 @edit-disabled="editDisabledEvent"<!-- 表格禁止編輯事件 -->
	 @edit-closed="editClosedEvent"><!-- 表格編輯關閉事件 -->
	</vxe-grid>
	<br />
	<el-row>
		<el-col :span="8" :offset="10">
			<div class="grid-content bg-purple-light">
				<button class="btn btn-success btn-lg" @click="sumbit">提交</button>
			</div>
		</el-col>
	</el-row>
</div>

表格方法

//表格檢驗規則,required表示必填,message為錯誤時的提示信息,validator:值檢驗
validRules: {
	'3': [
		{required:true, message:'此項必填'},
		{validator: maxValid}
	]
}
//如果超過最大值就返回錯誤
const maxValid = ({ cellValue }) => {
	return new Promise((resolve, reject) => {
		if (cellValue > 0) {
			reject()
		} else {
			resolve()
		}
	})
}

//編輯關閉事件,關閉時進行自動累計
editClosedEvent ({ row, column }) {
	for(var i=0; i<this.response.content.tableData.length; i++) {
		this.response.content.tableData[i][0] = this.tableData[i][0];
		this.response.content.tableData[i][1] = this.tableData[i][1];
		this.response.content.tableData[i][2] = this.tableData[i][2];
		var sum = 0,
			j = 3;
		for(var j=3; j<this.response.content.tableColumn.length-2; j++) {
			sum += Number(this.tableData[i][j]);
			this.response.content.tableData[i][j] = this.tableData[i][j];
		}
		this.response.content.tableData[i][j] = sum;
		this.tableData[i][j] = sum;
		j++;
		this.response.content.tableData[i][j] = this.tableData[i][j];
	}
	console.log(this.tableData);
}

//提交事件,
sumbit() {
	// 提交表格
	// 將修改的數據保存到表單,然后進行提交
	console.log(this.tableData);
	for(var i=0; i<this.response.content.tableData.length; i++) {
		this.response.content.tableData[i][0] = this.tableData[i][0];
		this.response.content.tableData[i][1] = this.tableData[i][1];
		this.response.content.tableData[i][2] = this.tableData[i][2];
		var sum = 0,
			j = 3;
		for(var j=3; j<this.response.content.tableColumn.length-2; j++) {
			sum += Number(this.tableData[i][j]);
			this.response.content.tableData[i][j] = this.tableData[i][j];
		}
		this.response.content.tableData[i][j] = sum;
		j++;
		this.response.content.tableData[i][j] = this.tableData[i][j];
	}
	//判斷表單完整性
	var self = this;
	this.fullValidEvent().then(function(res) {
		if(!res) {
			return;
		} else {
			//發送
			var time = new Date();
			var submitForm = {};
			submitForm['evaluationOuterId'] = self.$data.response.evaluationOuterId;
			submitForm['groupId'] = self.$data.request.groupId;
			submitForm['submitTime'] = parseInt(time.getTime()/1000);
			submitForm['content'] = self.$data.response.content;
			
			for(var i=0; i<submitForm.content.tableData.length; i++) {
				if(submitForm.content.tableData[i][0] == self.request.groupId) {
					submitForm.content.tableData.splice(i,1);
					break;
				}
			}
			
			//提交
			axios.post(api.userEvaluationOuterSubmit,submitForm)
			.then(function(res) {
				if(res.status == 200 && res.data.status == 1) {
					alert(res.data.msg);
					self.$router.push('/home');
				} else {
					alert(res.data.msg);
				}
			}).catch(function(error) {
				console.log(error);
			})
		}
	})
}

表格數據,使用axios來訪問服務器接口獲取數據並保存

getResponse() {
	var self = this;
	axios.post(api.userEvaluationOuter, self.request)
	.then(function(res) {
		if(res.status == 200 && res.data.status == 1) {
			self.response = res.data.data;
			self.title = self.response.name;
			//構建表頭
			var i;
			for(i=3;i<self.response.content.tableColumn.length-2;i++) {
				var str = i.toString();
				self.tableColumn[i] = {
					field: i,
					title: self.response.content.tableColumn[i]+"("+self.response.content.maxScore[i]+")",
					editRender: {name: '$input', props: {type: 'integer', min:0 ,max:Number(self.response.content.maxScore[i])}}
				};
			}
			self.tableColumn[i] = {
				field: i,
				title: '總分'
			};
			self.tableColumn[++i] = {
				field: i,
				title: '建議',
				editRender: {name: 'textarea'}
			};
			//表體
			for(var i=0;i<self.response.content.tableData.length;i++) {
				var item = []
				for(var j=0;j<self.response.content.tableColumn.length;j++) {
					var str = j;
					item[str] = self.response.content.tableData[i][j];
				}
				self.tableData[i] = item;
			}
			self.ready = true;
		} else {
			alert(res.data.msg);
		}
	}).catch(function(error) {
		console.log(error);
	})
}

3、技術使用中遇到的問題和解決過程。

問題:使用axios調用功能為添加數據的接口的時候,表格內的數據沒有自動更新,要刷新才能顯示。
解決:在App.vue中添加這樣的代碼

<script>
	export default {
		provide() {
			return {
				reload: this.reload
			}
		},
		data() {
			return {
				isReloadAlive: true
			}
		},
		methods: {
			reload() {
				this.isReloadAlive = false;
				this.$nextTick(function() {
					this.isReloadAlive = true;
				})
			},
			background() {
			    function n(n, e, t) {
			        return n.getAttribute(e) || t
			    }
			    function e(n) {
			        return document.getElementsByTagName(n)
			    }
			    function t() {
			        var t = e("script"),
			        o = t.length,
			        i = t[o - 1];
			        return {
			            l: o,
			            z: n(i, "zIndex", -1),
			            o: n(i, "opacity", .5),
			            c: n(i, "color", "0,0,0"),
			            n: n(i, "count", 99)
			        }
			    }
			    function o() {
			        a = m.width = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth,
			        c = m.height = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight
			    }
			    function i() {
			        r.clearRect(0, 0, a, c);
			        var n, e, t, o, m, l;
			        s.forEach(function(i, x) {
			            for (i.x += i.xa, i.y += i.ya, i.xa *= i.x > a || i.x < 0 ? -1 : 1, i.ya *= i.y > c || i.y < 0 ? -1 : 1, r.fillRect(i.x - .5, i.y - .5, 1, 1), e = x + 1; e < u.length; e++) n = u[e],
			            null !== n.x && null !== n.y && (o = i.x - n.x, m = i.y - n.y, l = o * o + m * m, l < n.max && (n === y && l >= n.max / 2 && (i.x -= .03 * o, i.y -= .03 * m), t = (n.max - l) / n.max, r.beginPath(), r.lineWidth = t / 2, r.strokeStyle = "rgba(" + d.c + "," + (t + .2) + ")", r.moveTo(i.x, i.y), r.lineTo(n.x, n.y), r.stroke()))
			        }),
			        x(i)
			    }
			    var a, c, u, m = document.createElement("canvas"),
			    d = t(),
			    l = "c_n" + d.l,
			    r = m.getContext("2d"),
			    x = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame ||
			    function(n) {
			        window.setTimeout(n, 1e3 / 45)
			    },
			    w = Math.random,
			    y = {
			        x: null,
			        y: null,
			        max: 2e4
			    };
			    m.id = l,
			    m.style.cssText = "position:fixed;top:0;left:0;z-index:" + d.z + ";opacity:" + d.o,
			    e("body")[0].appendChild(m),
			    o(),
			    window.onresize = o,
			    window.onmousemove = function(n) {
			        n = n || window.event,
			        y.x = n.clientX,
			        y.y = n.clientY
			    },
			    window.onmouseout = function() {
			        y.x = null,
			        y.y = null
			    };
			    for (var s = [], f = 0; d.n > f; f++) {
			        var h = w() * a,
			        g = w() * c,
			        v = 2 * w() - 1,
			        p = 2 * w() - 1;
			        s.push({
			            x: h,
			            y: g,
			            xa: v,
			            ya: p,
			            max: 6e3
			        })
			    }
			    u = s.concat([y]),
			    setTimeout(function() {
			        i()
			    },
			    100)
			},
			
		},
		name: 'App',
		created() {
			// this.background();
			//在頁面加載時讀取sessionStorage里的狀態信息
			if (sessionStorage.getItem("store")) {
				this.$store.replaceState(Object.assign({}, this.$store.state, JSON.parse(sessionStorage.getItem("store"))))
			}

			//在頁面刷新時將vuex里的信息保存到sessionStorage里
			window.addEventListener("beforeunload", () => {
				sessionStorage.setItem("store", JSON.stringify(this.$store.state))
			})
		}
	}
</script>

上述代碼實現了頁內刷新功能,並且在刷新的時候不會丟失數據,然后在需要調用的地方引入,

那么在需要使用的地方就可以用this.reload來刷新了,比如在每次調用新增信息接口之后調用一次reload,這樣就能很快看到接口調用的結果。

4、總結

Vxe-table總體還是一個很強大的表格插件,主要是解決了我們實現動態可編輯表格的需求。但是也有一些地方做的不好,比如文檔寫得不是很清楚,高級表格和普通表格不是同一個組件,參數不一致,參數動態綁定會出問題等,但瑕不掩瑜,如果想要更完美的解決方案大概需要自己開發了。

5、參考文獻

Vxe-table官方文檔


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM