通过 v-for 循环的列表,点击一项只对这一项产生相应的操作

在 vue 项目中,通过 v-for 循环出的买家秀中,点赞功能,点击一项只对这一项有作用

首先,在组件中,两个点赞图标,这里使用阿里巴巴矢量图标库, v-if 和 v-else 显示其中一个。如下代码

            <p class="zan">
              <i class="icon iconfont icon-weibiaoti--" v-if="item.flag" @click="dianZan(i)"></i>
              <i class="icon iconfont icon-weibiaoti--" style="color: crimson" v-else @click="dianZan(i)"></i>
              <span>{{ item.zanNum }}</span>
            </p>

数据库中,存放着点赞的数量及标识符flag, “flag”:true ,默认未点赞

刚开始错误做法:

数据库中没有flag标识符和zanNum,只在data中定义flag:true,num:0

1             if (this.flag) {
2               this.flag = false;
3               this.num++
4             } else {
5               this.flag = true;
6               this.num--
7             }

然后 localStorage.setItem('weiWeiTaoZanNum',this.num) 存放进本地浏览器中,在进入页面时,在生命周期函数created中调用 this.num = localStorage.getItem('weiWeiTaoZanNum'); 

这种做法的确可以实现点赞和图标变化,但是点其中一项,其余全部会变

正确做法:

数据库中存放flag标识符,点击事件中将 索引传递过来,然后some遍历数据数组,找到相同索引那一项,判断是否点过赞, array[i].flag = true 时,表示还未点赞,为 false 时,已经点过赞,且点赞图标已经变为红色,在点一次就要取消赞,flag变为 true ,接着将改变后的对象传给后台,更新数据库中的数据。

代码如下:

      methods:{
        dainZan(i){ // i 表示当前点击的那一项
          // console.log(i)
          this.List.some((value, index, array) => {
            // console.log(index)
            // console.log(array)
            if (i === index) {
              if (array[i].flag) {
                array[i].zan++;
                array[i].flag = false
              } else {
                array[i].zan--;
                array[i].flag = true
              }
              // console.log(array[i])
              const zanObj = array[i];
                this.$axios.post('/updatezan',zanObj).then((res) => {
                  // 更新赞
                })
)}
}
}

成品图:

猜你喜欢

转载自www.cnblogs.com/zhaohui-116/p/12317626.html