由于 JavaScript 的限制锦秒,Vue 不能檢測以下變動(dòng)的數(shù)組:
當(dāng)你利用索引直接設(shè)置一個(gè)項(xiàng)時(shí)乳丰,例如:vm.items[indexOfItem] = newValue
當(dāng)你修改數(shù)組的長度時(shí),例如:vm.items.length = newLength
對(duì)象更改檢測注意事項(xiàng):
還是由于 JavaScript 的限制霎桅,Vue 不能檢測對(duì)象屬性的添加或刪除
實(shí)例:
點(diǎn)擊選中標(biāo)簽栖疑,再次點(diǎn)擊取消選中,提交時(shí)把最終選中標(biāo)簽的值存入數(shù)組傳給后端
image.png
//原理:通過給一個(gè)對(duì)象添加key value作為標(biāo)識(shí) isActive: 'selected'
data() {
return {
skinTypeList:[
{
key: '干燥',
value: 'DRY'
},
{
key: '松弛',
value: 'RELAXATION'
},
{
key: '色斑',
value: 'SPLASH'
}
],
btnDisable: false //提交時(shí)做個(gè)標(biāo)識(shí)
}
}
//點(diǎn)擊時(shí)執(zhí)行方法如下:
selectTag(index){
let item = this.skinTypeList[index]
let oldArr = {
key: item.key,
value: item.value
}
let newArr = {
key: item.key,
value: item.value,
isActive: 'selected'
}
if(item.isActive === 'selected'){
this.skinTypeList.splice(index,1,oldArr) //如標(biāo)簽為選中狀態(tài),再次點(diǎn)擊時(shí)重新構(gòu)造數(shù)組, 取消選中
let arrIndex = this.saveTagList.indexOf(item.value) //找當(dāng)前item.value在saveTagList中的位置滔驶,并刪掉
this.saveTagList.splice(arrIndex,1) // 重新構(gòu)造saveTagList數(shù)組
} else {
this.skinTypeList.splice(index,1,newArr)//如點(diǎn)擊前是不選中狀態(tài),那么點(diǎn)擊時(shí)重新構(gòu)造數(shù)組,為選中狀態(tài)
this.saveTagList.push(item.value) // 并把item.value push進(jìn)數(shù)組
}
}
//提交時(shí)執(zhí)行方法如下:
//提交時(shí)前置手機(jī)號(hào)和年齡不能為空
submitFace(){
if(this.ageNum && this.phoneNum){
if(this.btnDisable) return //防止多次提交不斷發(fā)請(qǐng)求
wepy.showLoading({
title: '提交中...',
mask: true
})
this.btnDisable = true //防止多次提交不斷發(fā)請(qǐng)求
wepy.request({
url: '/mobile/mina/face/save',
method: 'POST',
data: {
age: this.ageNum,
phone: this.phoneNum,
problemTypeList: this.saveTagList
}
}).then((res) => {
if (res.resCode != 0) return
wepy.showToast({
title: '信息提交成功',
icon: 'success',
duration: 2000
})
this.showFaceDia = false
this.phoneNum = ''
this.ageNum = ''
this.saveTagList = [] //防止再次push累加上一次的值
this.skinTypeList.forEach((item)=>{
if(item.isActive) item.isActive=''
})
this.$apply()
})
}
}