vue實現(xiàn)靜態(tài)頁面點贊和取消點贊功能
本文實例為大家分享了vue實現(xiàn)靜態(tài)頁面點贊和取消點贊的具體代碼,供大家參考,具體內(nèi)容如下
效果如下:
點擊之后 點贊數(shù)量+1,紅心亮
再次點擊,點贊數(shù)量-1,紅心滅


邏輯:
由于列表是動態(tài)渲染的(for),數(shù)據(jù)是mock隨機生成,所以綁定點擊事件時,應(yīng)該把當前下標和item的id都傳到事件上,在data里面聲明空數(shù)組,用來存放已經(jīng)點擊的id,
點贊點擊事件觸發(fā),先進行判斷,
1.當前data內(nèi)的數(shù)組是否有這個點擊的id,用indexof方法查找,如果找不到,執(zhí)行點贊功能,數(shù)量+1,紅心樣式取反,最重要的是將當前點贊的id存到data的數(shù)組里 push進去。
2.反之找到了,就將他數(shù)量-1,心取消。
for遍歷data的數(shù)組,目的是為了找到當前點擊的id的下標,找到后,直接利用splice刪除的放法,splice(i,1)第一個參數(shù)為下標,第二個刪除一個,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"></i>
? ? ? ? ? <i class="iconfont" v-else></i>
? ? ? ? ? <span>{{ item.dianzan }}</span>
? ? ? ? </div>
? ? ? ? <div class="pinglun">
? ? ? ? ? <i class="iconfont"></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) {
? ? ? ? // 沒找到
? ? ? ? // 執(zhí)行點贊功能
? ? ? ? this.foodMeishi[index].dianzan += 1;
? ? ? ? // 加到數(shù)組中
? ? ? ? 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>
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
基于Vue3.0開發(fā)輕量級手機端彈框組件V3Popup的場景分析
這篇文章主要介紹了基于Vue3.0開發(fā)輕量級手機端彈框組件V3Popup,本文通過場景分析給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-12-12
element plus中el-upload實現(xiàn)上傳多張圖片的示例代碼
最近寫項目的時候需要一次上傳多張圖片,本文主要介紹了element plus中el-upload實現(xiàn)上傳多張圖片的示例代碼,具有一定的參考價值,感興趣的可以了解一下2024-01-01

