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

发布时间:2022-02-24 16:36:37 作者:iii
来源:亿速云 阅读:488

本文小编为大家详细介绍“vue怎么实现静态页面点赞和取消点赞功能”,内容详细,步骤清晰,细节处理妥当,希望这篇“vue怎么实现静态页面点赞和取消点赞功能”文章能帮助大家解决疑惑,下面跟着小编的思路慢慢深入,一起来学习新知识吧。

效果如下:

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

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

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

逻辑:

由于列表是动态渲染的(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怎么实现静态页面点赞和取消点赞功能”文章已经介绍完毕,想要掌握这篇文章的知识点还需要大家自己动手实践使用过才能领会,如果想了解更多相关内容的文章,欢迎关注亿速云行业资讯频道。

推荐阅读:
  1. 点赞和取消代码(jquery)
  2. 如何在微信小程序中实现点赞、取消点赞功能

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

vue

上一篇:怎么用java多态实现电子宠物系统

下一篇:javascript对象分为哪些类型

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》