vuejs如何清空表單數(shù)據(jù)、刪除對象中的空屬性公共方法
更新時間:2025年03月27日 08:37:37 作者:Lemon今天學(xué)習(xí)了嗎
這篇文章主要介紹了vuejs如何清空表單數(shù)據(jù)、刪除對象中的空屬性公共方法,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
vuejs清空表單數(shù)據(jù)、刪除對象中的空屬性公共方法
對于復(fù)雜數(shù)據(jù),使用element自帶的方法可能不能滿足我們的需求,所以可以封裝一個公共方法在全局。
一、清空表單數(shù)據(jù)
// 取消
canalHandle() {
this.resetValue(this.ruleForm)
this.dialogVisible = false
},
//------------------ 公共方法 ---------------------------
// 重置條件
returnNormalValue(value) {
if (typeof value === 'string') {
return ''
}
if (typeof value === 'number') {
return 0
}
const toStrong = Object.prototype.toString
const type = toStrong.call(value)
if (type.includes('Date')) {
return new Date()
}
if (type.includes('Object')) {
return {}
}
if (type.includes('Array')) {
return []
}
},
// 重置條件
resetValue(data) {
const searchForm = data
for (const key in searchForm) {
if (Object.hasOwnProperty.call(searchForm, key)) {
searchForm[key] = this.returnNormalValue(searchForm[key])
}
}
}二、刪除對象中的空屬性
//使用方式
let params = {
pageNum: this.pagesUp.pageNum,
pageSize: this.pagesUp.pageSize,
viewId: this.currentViewId,
...this.searchForm
}
params = delNullProperty(params)
//------------------------ 公共方法 --------------------------------
/**
* 刪除對象中的空屬性
* @param obj
* @returns
*/
export const delNullProperty = (obj) => {
if (!obj) return
const temp = JSON.parse(JSON.stringify(obj))
for (const i in temp) {
// 遍歷對象中的屬性
if (temp[i] === undefined || temp[i] === null || temp[i] === '') {
// 首先除去常規(guī)空數(shù)據(jù),用delete關(guān)鍵字
delete temp[i]
} else if (temp[i].constructor === Object) {
// 如果發(fā)現(xiàn)該屬性的值還是一個對象,再判空后進行迭代調(diào)用
if (Object.keys(temp[i]).length === 0) delete temp[i] // 判斷對象上是否存在屬性,如果為空對象則刪除
delNullProperty(temp[i])
} else if (temp[i].constructor === Array) {
// 對象值如果是數(shù)組,判斷是否為空數(shù)組后進入數(shù)據(jù)遍歷判空邏輯
if (temp[i].length === 0) {
// 如果數(shù)組為空則刪除
delete temp[i]
} else {
for (let index = 0; index < temp[i].length; index++) {
// 遍歷數(shù)組
if (
temp[i][index] === undefined ||
temp[i][index] === null ||
temp[i][index] === '' ||
JSON.stringify(temp[i][index]) === '{}'
) {
temp[i].splice(index, 1) // 如果數(shù)組值為以上空值則修改數(shù)組長度,移除空值下標后續(xù)值依次提前
index-- // 由于數(shù)組當(dāng)前下標內(nèi)容已經(jīng)被替換成下一個值,所以計數(shù)器需要自減以抵消之后的自增
}
if (temp[i].constructor === Object) {
// 如果發(fā)現(xiàn)數(shù)組值中有對象,則再次進入迭代
delNullProperty(temp[i])
}
}
}
}
}
return temp
}總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
Vue3中使用exceljs和file-saver實現(xiàn)Excel導(dǎo)出(含圖片導(dǎo)出)功能完整方案
ExcelJS是一個用于在Node.js和瀏覽器中創(chuàng)建、讀取和修改Excel文件的強大JavaScript庫,這篇文章主要介紹了Vue3中使用exceljs和file-saver實現(xiàn)Excel導(dǎo)出(含圖片導(dǎo)出)功能的相關(guān)資料,需要的朋友可以參考下2025-07-07
vue子組件如何獲取父組件的內(nèi)容(props屬性)
這篇文章主要介紹了vue子組件獲取父組件的內(nèi)容(props屬性),具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-04-04
Vue中的情侶屬性$dispatch和$broadcast詳解
這篇文章主要給大家介紹了關(guān)于Vue中情侶屬性$dispatch和$broadcast的相關(guān)資料,文中通過示例代碼以及圖文介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面來一起學(xué)習(xí)學(xué)習(xí)吧2019-03-03

