最近,在開發項目的時候,要做一個手風琴,要求能**同時展開多個面板**,喏,也就是Element-ui 摺疊面板這個型的:
但需求是加了更改排序的功能,如下圖,表現上自然不同了,先前提到的Element-ui摺疊面板,滿足不了,只能 DIY 一個。
接着,啪嘰一頓代碼下來,大體如下。這裏的方法是:給已有的數據對象添加新的屬性。
[color=#ff4753]*[/color]注:當然用 DOM、ref 的方法也能解決,但總感覺有種騎馬上高速的感覺。
<template>
<div class="accord">
<div v-for="(item,index) in showCars" :key="index" class="accord">
<div class="hd" @click="accord(index)">title</div>
<div class="bd" v-show="item.show">context</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
showCars:[],
}
},
created(){
this.init()
},
methods:{
init(){
this.$fetch.crownpin.carManageShowCars().then((res)=>{
this.showCars = res.data.cars;
for(let i in this.showCars){
i.show = false
}
}).catch((res)=>{
})
},
accord(index){
this.showCars[index].show = !this.showCars[index].show
console.log(this.showCars[index])
},
}
}
</script>
再來點擊手風琴,發現沒效果,但事件其實是響應的,當前項的 show 也是變化的,那爲什麼沒反應呢?
想必你也想到了,沒錯,新增的屬性數據不響應!!!
準確的說辭是:受 ES5 的限制,Vue.js 不能檢測到對象屬性的添加或刪除。因爲 Vue.js 在初始化實例時將屬性轉爲 getter/setter,所以屬性必須在 data 對象上才能讓 Vue.js 轉換它,才能讓它是響應的。
找到問題,於是就順藤摸瓜找到了 $set():既可以新增屬性,又可以觸發視圖更新。
提示:$set官檔,跟 $set 組合的,還有 $delete,與此無關,暫時不表。
稍加修改,試試!卡拉 o-k [qq:95]!!!
<template>
<div class="accord">
<div v-for="(item,index) in showCars" :key="index" class="accord">
<div class="hd" @click="accord(index)">title</div>
<div class="bd" v-show="item.show">context</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
showCars:[],
}
},
created(){
this.init()
},
methods:{
init(){
this.$fetch.crownpin.carManageShowCars().then((res)=>{
this.showCars = res.data.cars;
for(let i in this.showCars){
this.$set(this.showCars[i],'show',false);
}
}).catch((res)=>{
})
},
accord(index){
this.showCars[index].show = !this.showCars[index].show
},
}
}
</script>