vuejs如何清空表單數(shù)據(jù)、刪除對象中的空屬性公共方法
更新時間:2025年03月27日 08:37:37 作者:Lemon今天學習了嗎
這篇文章主要介紹了vuejs如何清空表單數(shù)據(jù)、刪除對象中的空屬性公共方法,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
vuejs清空表單數(shù)據(jù)、刪除對象中的空屬性公共方法
對于復雜數(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關鍵字
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ù)組當前下標內(nèi)容已經(jīng)被替換成下一個值,所以計數(shù)器需要自減以抵消之后的自增
}
if (temp[i].constructor === Object) {
// 如果發(fā)現(xiàn)數(shù)組值中有對象,則再次進入迭代
delNullProperty(temp[i])
}
}
}
}
}
return temp
}總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
vue實現(xiàn)echarts餅圖/柱狀圖點擊事件實例
echarts原生提供了相應的API,只需要在配置好echarts之后綁定相應的事件即可,下面這篇文章主要給大家介紹了關于vue實現(xiàn)echarts餅圖/柱狀圖點擊事件的相關資料,需要的朋友可以參考下2023-06-06
vue百度地圖通過地址名稱獲取地址的經(jīng)緯度gps問題(具體步驟)
在Vue項目中,可以通過使用百度地圖JavaScript?API來實現(xiàn)根據(jù)地址名稱獲取經(jīng)緯度GPS的功能,本文分步驟給大家詳細講解vue百度地圖獲取經(jīng)緯度的實例,感興趣的朋友一起看看吧2023-05-05
vue中三種插槽(默認插槽/具名插槽/作用域插槽)的區(qū)別詳解
默認插槽,具名插槽,作用域插槽是vue中常用的三個插槽,這篇文章主要為大家介紹了這三種插槽的使用與區(qū)別,感興趣的小伙伴可以了解一下2023-08-08
vue.js 使用v-if v-else發(fā)現(xiàn)沒有執(zhí)行解決辦法
這篇文章主要介紹了vue.js 使用v-if v-else發(fā)現(xiàn)沒有執(zhí)行解決辦法的相關資料,需要的朋友可以參考下2017-05-05

