Vue 手风琴 和 $set

   最近,在开发项目的时候,要做一个手风琴,要求能**同时展开多个面板**,喏,也就是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>


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值