vue实现静态页面点赞和取消点赞功能

Iris ·
更新时间:2024-09-20
· 284 次阅读

本文实例为大家分享了vue实现静态页面点赞和取消点赞的具体代码,供大家参考,具体内容如下

效果如下:

点击之后 点赞数量+1,红心亮
再次点击,点赞数量-1,红心灭

逻辑:

由于列表是动态渲染的(for),数据是mock随机生成,所以绑定点击事件时,应该把当前下标和item的id都传到事件上,在data里面声明空数组,用来存放已经点击的id,
点赞点击事件触发,先进行判断,
1.当前data内的数组是否有这个点击的id,用indexof方法查找,如果找不到,执行点赞功能,数量+1,红心样式取反,最重要的是将当前点赞的id存到data的数组里 push进去。
2.反之找到了,就将他数量-1,心取消。
for遍历data的数组,目的是为了找到当前点击的id的下标,找到后,直接利用splice删除的放法,splice(i,1)第一个参数为下标,第二个删除一个,vue组件代码如下:

<template>   <div v-if="foodMeishi">     <div       class="food-box-content"       v-for="(item, index) in foodMeishi"       :key="item.id"     >       <img class="food-photo" :src="item.foodphotoUrl" alt="" />       <div class="head">         <img :src="item.headImg" alt="" />         <p class="head-name">{{ item.headName }}</p>       </div>       <div class="food-content">         {{ item.content }}       </div>       <div class="food-bottom">         <div class="xin" @click="dianzan(index, item.id)">           <i class="iconfont " v-if="item.xin">&#xe607;</i>           <i class="iconfont" v-else>&#xe68b;</i>           <span>{{ item.dianzan }}</span>         </div>         <div class="pinglun">           <i class="iconfont">&#xe603;</i>           <span>{{ item.pinglun }}</span>         </div>       </div>     </div>   </div> </template> <script> export default {   props: ["foodMeishi"],   data() {     return {       zanListId: [1, 2],     };   },   methods: {     dianzan(index, id) {       let list = this.zanListId;       if (list.indexOf(id) == -1) {         // 没找到         // 执行点赞功能         this.foodMeishi[index].dianzan += 1;         // 加到数组中         this.zanListId.push(id);         this.foodMeishi[index].xin = !this.foodMeishi[index].xin;       } else {         // 取消点赞         this.foodMeishi[index].dianzan -= 1;         this.foodMeishi[index].xin = !this.foodMeishi[index].xin;         for (var i in this.zanListId) {           if (this.zanListId[i] == id) {             this.zanListId.splice(i, 1);           }         }       }     },   }, }; </script>



VUE 静态 静态页面

需要 登录 后方可回复, 如果你还没有账号请 注册新账号