【商城实战(73)】商城社交互动功能大升级:解锁用户活跃新密码

【商城实战】专栏重磅来袭!这是一份专为开发者与电商从业者打造的超详细指南。从项目基础搭建,运用 uniapp、Element Plus、SpringBoot 搭建商城框架,到用户、商品、订单等核心模块开发,再到性能优化、安全加固、多端适配,乃至运营推广策略,102 章内容层层递进。无论是想深入钻研技术细节,还是探寻商城运营之道,本专栏都能提供从 0 到 1 的系统讲解,助力你打造独具竞争力的电商平台,开启电商实战之旅。

目录

  • 一、用户关注功能实现
    • 1.1 功能描述
    • 1.2 前端实现
      • 1.2.1 uniapp 实现
      • 1.2.2 Element Plus 实现
    • 1.3 后端实现
    • 1.4 代码示例
      • 1.4.1 uniapp 前端代码示例
      • 1.4.2 Element Plus 前端代码示例
      • 1.4.3 Spring Boot 后端代码示例
  • 二、点赞、评论功能实现
    • 2.1 功能描述
    • 2.2 前端实现
      • 2.2.1 uniapp 实现
      • 2.2.2 Element Plus 实现
    • 2.3 后端实现
    • 2.4 代码示例
      • 2.4.1 uniapp 点赞、评论功能代码示例
      • 2.4.2 Element Plus 点赞、评论功能代码示例
      • 2.4.3 Spring Boot 后端点赞、评论功能代码示例
  • 三、社交互动激励机制设计
    • 3.1 功能描述
    • 3.2 前端实现
      • 3.2.1 uniapp 实现
      • 3.2.2 Element Plus 实现
    • 3.3 后端实现
    • 3.4 代码示例
      • 3.4.1 uniapp 前端代码示例
      • 3.4.2 Element Plus 前端代码示例
      • 3.4.3 Spring Boot 后端代码示例
  • 四、总结


一、用户关注功能实现

1.1 功能描述

用户关注功能允许用户关注感兴趣的店铺与其他用户,从而增强用户之间以及用户与店铺之间的社交互动。通过关注,用户可以方便地获取被关注对象的动态,如店铺上新、用户发布的内容等,同时也为用户之间建立更紧密的联系提供了基础。

1.2 前端实现

1.2.1 uniapp 实现

在 uniapp 中,我们可以使用 Vuex 来管理状态。首先,在 Vuex 的 state 中定义一个数组followingList,用于存储用户关注的对象 ID 列表。在需要实现关注功能的页面中,通过dispatch方法触发一个 action。例如:

// methods中
methods: {
    follow(userId) {
        this.$store.dispatch('followUser', userId);
    }
}

在 Vuex 的 actions 中,定义followUser方法,通过uni.request向后端发送关注请求:

actions: {
    async followUser({ commit }, userId) {
        const res = await uni.request({
            url: 'http://your-backend-api/follow',
            method: 'POST',
            data: {
                userId: userId
            }
        });
        if (res.statusCode === 200) {
            commit('followUser', userId);
        }
    }
}

在 mutations 中,定义followUser方法来更新followingList:

mutations: {
    followUser(state, userId) {
        state.followingList.push(userId);
    }
}

1.2.2 Element Plus 实现

在 PC 前端使用 Element Plus 时,我们可以利用el-drawer组件实现一个侧边弹出窗口,用于显示用户的粉丝和关注列表。利用el-card和el-table组件来展示粉丝或关注列表的用户数据。

<el-drawer :visible.sync="drawerVisible" title="关注列表">
    <el-table :data="followingList">
        <el-table-column prop="nickName" label="昵称"></el-table-column>
        <el-table-column label="操作">
            <template #default="scope">
                <el-button v-if="!isFollowed(scope.row.id)" @click="follow(scope.row.id)">关注</el-button>
                <el-button v-else @click="unfollow(scope.row.id)">取消关注</el-button>
            </template>
        </el-table-column>
    </el-table>
</el-drawer>

import { ref } from 'vue';

export default {
    setup() {
        const drawerVisible = ref(false);
        const followingList = ref([]);

        const isFollowed = (userId) => {
            // 判断是否已关注的逻辑
            return followingList.value.some(item => item.id === userId);
        };

        const follow = async (userId) => {
            // 发送关注请求的逻辑
            const res = await fetch('http://your-backend-api/follow', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ userId: userId })
            });
            if (res.ok) {
                const data = await res.json();
                followingList.value.push({ id: userId });
            }
        };

        const unfollow = async (userId) => {
            // 发送取消关注请求的逻辑
            const res = await fetch('http://your-backend-api/unfollow', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ userId: userId })
            });
            if (res.ok) {
                followingList.value = followingList.value.filter(item => item.id!== userId);
            }
        };

        return {
            drawerVisible,
            followingList,
            isFollowed,
            follow,
            unfollow
        };
    }
};

1.3 后端实现

在 Spring Boot 中,定义接收前端关注请求的接口。例如:

@RestController
@RequestMapping("/follow")
public class FollowController {
    @Autowired
    private FollowService followService;

    @PostMapping
    public Result follow(@RequestBody FollowDTO followDTO) {
        followService.follow(followDTO);
        return Result.success("关注成功");
    }
}

在服务层,利用 MyBatis-Plus 的IService接口来实现关注数据的存储和操作。首先定义Follow实体类和FollowService接口,并继承IService。在FollowServiceImpl中实现关注方法:

@Service
public class FollowServiceImpl extends ServiceImpl<FollowMapper, Follow> implements FollowService {
    @Override
    public void follow(FollowDTO followDTO) {
        Follow follow = new Follow();
        follow.setUserId(followDTO.getUserId());
        follow.setFollowedId(followDTO.getFollowedId());
        this.save(follow);
    }
}

1.4 代码示例

1.4.1 uniapp 前端代码示例

  • Vuex 配置文件store.js
import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);

export default new Vuex.Store({
    state: {
        followingList: []
    },
    mutations: {
        followUser(state, userId) {
            state.followingList.push(userId);
        }
    },
    actions: {
        async followUser({ commit }, userId) {
            const res = await uni.request({
                url: 'http://your-backend-api/follow',
                method: 'POST',
                data: {
                    userId: userId
                }
            });
            if (res.statusCode === 200) {
                commit('followUser', userId);
            }
        }
    }
});
  • 页面组件
<template>
    <view>
        <button @click="follow(1)">关注用户1</button>
    </view>
</template>

<script>
export default {
    methods: {
        follow(userId) {
            this.$store.dispatch('followUser', userId);
        }
    }
};
</script>

1.4.2 Element Plus 前端代码示例

<template>
    <el-button @click="drawerVisible = true">查看关注列表</el-button>
    <el-drawer :visible.sync="drawerVisible" title="关注列表">
        <el-table :data="followingList">
            <el-table-column prop="nickName" label="昵称"></el-table-column>
            <el-table-column label="操作">
                <template #default="scope">
                    <el-button v-if="!isFollowed(scope.row.id)" @click="follow(scope.row.id)">关注</el-button>
                    <el-button v-else @click="unfollow(scope.row.id)">取消关注</el-button>
                </template>
            </el-table-column>
        </el-table>
    </el-drawer>
</template>

<script setup>
import { ref } from 'vue';

const drawerVisible = ref(false);
const followingList = ref([]);

const isFollowed = (userId) => {
    return followingList.value.some(item => item.id === userId);
};

const follow = async (userId) => {
    const res = await fetch('http://your-backend-api/follow', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({ userId: userId })
    });
    if (res.ok) {
        const data = await res.json();
        followingList.value.push({ id: userId });
    }
};

const unfollow = async (userId) => {
    const res = await fetch('http://your-backend-api/unfollow', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({ userId: userId })
    });
    if (res.ok) {
        followingList.value = followingList.value.filter(item => item.id!== userId);
    }
};
</script>

1.4.3 Spring Boot 后端代码示例

  • Follow实体类
@Data
@TableName("follow")
public class Follow {
    @TableId(type = IdType.AUTO)
    private Long id;
    private Long userId;
    private Long followedId;
}
  • FollowService接口
public interface FollowService extends IService<Follow> {
    void follow(FollowDTO followDTO);
}
  • FollowServiceImpl实现类
@Service
public class FollowServiceImpl extends ServiceImpl<FollowMapper, Follow> implements FollowService {
    @Override
    public void follow(FollowDTO followDTO) {
        Follow follow = new Follow();
        follow.setUserId(followDTO.getUserId());
        follow.setFollowedId(followDTO.getFollowedId());
        this.save(follow);
    }
}
  • FollowController控制器
@RestController
@RequestMapping("/follow")
public class FollowController {
    @Autowired
    private FollowService followService;

    @PostMapping
    public Result follow(@RequestBody FollowDTO followDTO) {
        followService.follow(followDTO);
        return Result.success("关注成功");
    }
}
  • FollowDTO数据传输对象
@Data
public class FollowDTO {
    private Long userId;
    private Long followedId;
}

二、点赞、评论功能实现

2.1 功能描述

点赞和评论功能是增强用户社交互动的重要组成部分。用户可以对商品、店铺或者其他用户发布的内容进行点赞和评论,通过这种方式,用户之间能够分享自己的看法和喜好,促进信息的交流与传播。点赞功能能够快速表达用户对内容的喜爱或认可,而评论功能则为用户提供了更深入交流的平台,用户可以发表自己的观点、提出问题或者给予建议,这不仅增加了用户的参与感,还能提高用户对商城的粘性。

2.2 前端实现

2.2.1 uniapp 实现

在 uniapp 中实现点赞、评论功能,我们可以利用this.$set来修改视图层的数据,从而实现局部刷新。以商品详情页面为例,假设我们有一个商品列表,每个商品都有对应的点赞和评论功能。

首先,在页面的data中定义点赞状态和评论列表:

data() {
    return {
        productList: [],
        likeStatus: [],// 存储点赞状态,下标对应商品在productList中的下标
        commentList: []// 存储评论列表
    };
}

在模板中,为点赞按钮绑定点击事件likeProduct,为评论按钮绑定点击事件showCommentModal(假设点击评论按钮弹出评论模态框):

<template>
    <view>
        <view v-for="(product, index) in productList" :key="index">
            <text>{{ product.title }}</text>
            <button @click="likeProduct(index)">{{ likeStatus[index]? '已点赞' : '点赞' }}</button>
            <button @click="showCommentModal(index)">评论</button>
            <view v-for="(comment, commentIndex) in commentList[index]" :key="commentIndex">
                <text>{{ comment.content }}</text>
            </view>
        </view>
    </view>
</template>

在methods中实现点赞和显示评论模态框的方法:

methods: {
    async likeProduct(index) {
        const productId = this.productList[index].id;
        try {
            const res = await uni.request({
                url: 'http://your-backend-api/like',
                method: 'POST',
                data: {
                    productId: productId,
                    like:!this.likeStatus[index]
                }
            });
            if (res.statusCode === 200) {
                this.$set(this.likeStatus, index,!this.likeStatus[index]);
            }
        } catch (e) {
            console.error(e);
        }
    },
    showCommentModal(index) {
        // 显示评论模态框的逻辑,这里可以是打开一个新页面或者弹出模态框
    }
}

2.2.2 Element Plus 实现

在 Element Plus 中,我们通过组件和事件绑定来实现点赞、评论功能。以文章详情页面为例,使用el-button作为点赞和评论按钮,el-input和el-button组合实现评论提交功能,el-list来展示评论列表。

<template>
    <el-card>
        <h2>{{ article.title }}</h2>
        <el-button @click="likeArticle" :class="{ 'is-liked': isLiked }">{{ isLiked? '已点赞' : '点赞' }}</el-button>
        <span>点赞数: {{ likeCount }}</span>
        <el-button @click="showCommentForm = true">评论</el-button>
        <el-dialog :visible.sync="showCommentForm" title="发表评论">
            <el-form @submit.prevent="submitComment">
                <el-input v-model="commentContent" placeholder="请输入评论内容"></el-input>
                <el-button type="primary" native-type="submit">提交</el-button>
            </el-form>
        </el-dialog>
        <el-list :data="commentList">
            <template #default="{ item }">
                <el-list-item>
                    <p>{{ item.content }}</p>
                </el-list-item>
            </template>
        </el-list>
    </el-card>
</template>

<script setup>
import { ref } from 'vue';

const article = ref({});
const isLiked = ref(false);
const likeCount = ref(0);
const showCommentForm = ref(false);
const commentContent = ref('');
const commentList = ref([]);

const likeArticle = async () => {
    try {
        const res = await fetch('http://your-backend-api/like', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                articleId: article.value.id,
                like:!isLiked.value
            })
        });
        if (res.ok) {
            const data = await res.json();
            isLiked.value =!isLiked.value;
            likeCount.value = data.likeCount;
        }
    } catch (e) {
        console.error(e);
    }
};

const submitComment = async () => {
    if (commentContent.value.trim() === '') {
        return;
    }
    try {
        const res = await fetch('http://your-backend-api/comment', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                articleId: article.value.id,
                content: commentContent.value
            })
        });
        if (res.ok) {
            const newComment = await res.json();
            commentList.value.push(newComment);
            commentContent.value = '';
            showCommentForm.value = false;
        }
    } catch (e) {
        console.error(e);
    }
};
</script>

<style scoped>
.is-liked {
    color: red;
}
</style>

2.3 后端实现

在 Spring Boot 后端,我们创建相应的控制器来接收前端的点赞和评论请求。使用 MyBatis-Plus 来操作数据库,实现点赞数的更新和评论的插入。

首先,定义点赞和评论的数据实体类。假设点赞数据存储在like表中,评论数据存储在comment表中。

  • Like实体类
@Data
@TableName("like")
public class Like {
    @TableId(type = IdType.AUTO)
    private Long id;
    private Long userId;
    private Long targetId; // 可以是商品ID、文章ID等
    private Boolean like;
}
  • Comment实体类
@Data
@TableName("comment")
public class Comment {
    @TableId(type = IdType.AUTO)
    private Long id;
    private Long userId;
    private Long targetId;
    private String content;
    private LocalDateTime createTime;
}
  • 在控制器中,实现点赞和评论的接口
@RestController
@RequestMapping("/interaction")
public class InteractionController {
    @Autowired
    private LikeService likeService;
    @Autowired
    private CommentService commentService;

    @PostMapping("/like")
    public Result like(@RequestBody LikeDTO likeDTO) {
        likeService.like(likeDTO);
        return Result.success("点赞操作成功");
    }

    @PostMapping("/comment")
    public Result comment(@RequestBody CommentDTO commentDTO) {
        commentService.comment(commentDTO);
        return Result.success("评论成功");
    }
}
  • 在服务层中,实现点赞和评论的具体逻辑
@Service
public class LikeServiceImpl extends ServiceImpl<LikeMapper, Like> implements LikeService {
    @Override
    public void like(LikeDTO likeDTO) {
        QueryWrapper<Like> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", likeDTO.getUserId());
        wrapper.eq("target_id", likeDTO.getTargetId());
        Like like = this.getOne(wrapper);
        if (like == null) {
            like = new Like();
            like.setUserId(likeDTO.getUserId());
            like.setTargetId(likeDTO.getTargetId());
            like.setLike(likeDTO.getLike());
            this.save(like);
        } else {
            like.setLike(likeDTO.getLike());
            this.updateById(like);
        }
    }
}

@Service
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements CommentService {
    @Override
    public void comment(CommentDTO commentDTO) {
        Comment comment = new Comment();
        comment.setUserId(commentDTO.getUserId());
        comment.setTargetId(commentDTO.getTargetId());
        comment.setContent(commentDTO.getContent());
        comment.setCreateTime(LocalDateTime.now());
        this.save(comment);
    }
}

2.4 代码示例

2.4.1 uniapp 点赞、评论功能代码示例

  • 完整页面组件
<template>
    <view>
        <view v-for="(product, index) in productList" :key="index">
            <text>{{ product.title }}</text>
            <button @click="likeProduct(index)">{{ likeStatus[index]? '已点赞' : '点赞' }}</button>
            <button @click="showCommentModal(index)">评论</button>
            <view v-for="(comment, commentIndex) in commentList[index]" :key="commentIndex">
                <text>{{ comment.content }}</text>
            </view>
        </view>
    </view>
</template>

<script>
export default {
    data() {
        return {
            productList: [],
            likeStatus: [],
            commentList: []
        };
    },
    methods: {
        async likeProduct(index) {
            const productId = this.productList[index].id;
            try {
                const res = await uni.request({
                    url: 'http://your-backend-api/like',
                    method: 'POST',
                    data: {
                        productId: productId,
                        like:!this.likeStatus[index]
                    }
                });
                if (res.statusCode === 200) {
                    this.$set(this.likeStatus, index,!this.likeStatus[index]);
                }
            } catch (e) {
                console.error(e);
            }
        },
        showCommentModal(index) {
            // 显示评论模态框的逻辑,这里可以是打开一个新页面或者弹出模态框
        }
    },
    onLoad() {
        // 加载商品列表数据的逻辑
    }
};
</script>

2.4.2 Element Plus 点赞、评论功能代码示例

<template>
    <el-card>
        <h2>{{ article.title }}</h2>
        <el-button @click="likeArticle" :class="{ 'is-liked': isLiked }">{{ isLiked? '已点赞' : '点赞' }}</el-button>
        <span>点赞数: {{ likeCount }}</span>
        <el-button @click="showCommentForm = true">评论</el-button>
        <el-dialog :visible.sync="showCommentForm" title="发表评论">
            <el-form @submit.prevent="submitComment">
                <el-input v-model="commentContent" placeholder="请输入评论内容"></el-input>
                <el-button type="primary" native-type="submit">提交</el-button>
            </el-form>
        </el-dialog>
        <el-list :data="commentList">
            <template #default="{ item }">
                <el-list-item>
                    <p>{{ item.content }}</p>
                </el-list-item>
            </template>
        </el-list>
    </el-card>
</template>

<script setup>
import { ref } from 'vue';

const article = ref({});
const isLiked = ref(false);
const likeCount = ref(0);
const showCommentForm = ref(false);
const commentContent = ref('');
const commentList = ref([]);

const likeArticle = async () => {
    try {
        const res = await fetch('http://your-backend-api/like', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                articleId: article.value.id,
                like:!isLiked.value
            })
        });
        if (res.ok) {
            const data = await res.json();
            isLiked.value =!isLiked.value;
            likeCount.value = data.likeCount;
        }
    } catch (e) {
        console.error(e);
    }
};

const submitComment = async () => {
    if (commentContent.value.trim() === '') {
        return;
    }
    try {
        const res = await fetch('http://your-backend-api/comment', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                articleId: article.value.id,
                content: commentContent.value
            })
        });
        if (res.ok) {
            const newComment = await res.json();
            commentList.value.push(newComment);
            commentContent.value = '';
            showCommentForm.value = false;
        }
    } catch (e) {
        console.error(e);
    }
};

// 模拟获取文章数据
const getArticle = async () => {
    const res = await fetch('http://your-backend-api/article/1');
    if (res.ok) {
        const data = await res.json();
        article.value = data;
        // 模拟获取点赞数和评论列表
        likeCount.value = data.likeCount;
        commentList.value = data.commentList;
    }
};

getArticle();
</script>

<style scoped>
.is-liked {
    color: red;
}
</style>

2.4.3 Spring Boot 后端点赞、评论功能代码示例

  • LikeDTO数据传输对象
@Data
public class LikeDTO {
    private Long userId;
    private Long targetId;
    private Boolean like;
}
  • CommentDTO数据传输对象
@Data
public class CommentDTO {
    private Long userId;
    private Long targetId;
    private String content;
}
  • LikeService接口
public interface LikeService extends IService<Like> {
    void like(LikeDTO likeDTO);
}
  • CommentService接口
public interface CommentService extends IService<Comment> {
    void comment(CommentDTO commentDTO);
}
  • LikeServiceImpl实现类
@Service
public class LikeServiceImpl extends ServiceImpl<LikeMapper, Like> implements LikeService {
    @Override
    public void like(LikeDTO likeDTO) {
        QueryWrapper<Like> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", likeDTO.getUserId());
        wrapper.eq("target_id", likeDTO.getTargetId());
        Like like = this.getOne(wrapper);
        if (like == null) {
            like = new Like();
            like.setUserId(likeDTO.getUserId());
            like.setTargetId(likeDTO.getTargetId());
            like.setLike(likeDTO.getLike());
            this.save(like);
        } else {
            like.setLike(likeDTO.getLike());
            this.updateById(like);
        }
    }
}
  • CommentServiceImpl实现类
@Service
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements CommentService {
    @Override
    public void comment(CommentDTO commentDTO) {
        Comment comment = new Comment();
        comment.setUserId(commentDTO.getUserId());
        comment.setTargetId(commentDTO.getTargetId());
        comment.setContent(commentDTO.getContent());
        comment.setCreateTime(LocalDateTime.now());
        this.save(comment);
    }
}
  • InteractionController控制器
@RestController
@RequestMapping("/interaction")
public class InteractionController {
    @Autowired
    private LikeService likeService;
    @Autowired
    private CommentService commentService;

    @PostMapping("/like")
    public Result like(@RequestBody LikeDTO likeDTO) {
        likeService.like(likeDTO);
        return Result.success("点赞操作成功");
    }

    @PostMapping("/comment")
    public Result comment(@RequestBody CommentDTO commentDTO) {
        commentService.comment(commentDTO);
        return Result.success("评论成功");
    }
}

三、社交互动激励机制设计

3.1 功能描述

社交互动激励机制旨在通过给予用户一定的奖励,鼓励用户积极参与社交互动,如点赞、评论、分享等。其中点赞奖励积分是一种常见的激励方式,当用户对其他用户的内容进行点赞时,点赞者和被点赞者都可以获得相应的积分。这些积分可以用于兑换礼品、优惠券或者提升用户等级,从而提高用户的参与度和忠诚度。

3.2 前端实现

3.2.1 uniapp 实现

在 uniapp 中,我们可以在用户个人信息页面展示用户的积分。在点赞按钮的点击事件中,除了发送点赞请求,还需要更新积分显示。假设我们在data中定义了userScore来存储用户积分。

<template>
    <view>
        <text>我的积分: {{ userScore }}</text>
        <button @click="likeAndUpdateScore">点赞</button>
    </view>
</template>

<script>
export default {
    data() {
        return {
            userScore: 0
        };
    },
    methods: {
        async likeAndUpdateScore() {
            try {
                const res = await uni.request({
                    url: 'http://your-backend-api/like',
                    method: 'POST',
                    data: {
                        targetId: 1, // 假设点赞对象ID为1
                        like: true
                    }
                });
                if (res.statusCode === 200) {
                    const newScore = res.data.score;
                    this.userScore = newScore;
                    uni.showToast({
                        title: '点赞成功,积分增加',
                        icon:'success'
                    });
                }
            } catch (e) {
                console.error(e);
            }
        }
    },
    onLoad() {
        // 加载用户积分的逻辑
        uni.request({
            url: 'http://your-backend-api/user/score',
            method: 'GET',
            success: res => {
                if (res.statusCode === 200) {
                    this.userScore = res.data.score;
                }
            }
        });
    }
};
</script>

3.2.2 Element Plus 实现

在 Element Plus 中,我们可以在页面的头部或者侧边栏展示用户积分。使用el-tooltip组件来提示用户积分的用途。在点赞按钮的点击事件中,通过fetch发送点赞请求并更新积分显示。

<template>
    <el-container>
        <el-header>
            <span>我的积分: {{ userScore }}</span>
            <el-tooltip content="积分可用于兑换礼品和优惠券">
                <i class="el-icon-question"></i>
            </el-tooltip>
            <el-button @click="likeAndUpdateScore">点赞</el-button>
        </el-header>
        <el-main>
            <!-- 页面主要内容 -->
        </el-main>
    </el-container>
</template>

<script setup>
import { ref } from 'vue';

const userScore = ref(0);

const likeAndUpdateScore = async () => {
    try {
        const res = await fetch('http://your-backend-api/like', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                targetId: 1,
                like: true
            })
        });
        if (res.ok) {
            const data = await res.json();
            userScore.value = data.score;
            alert('点赞成功,积分增加');
        }
    } catch (e) {
        console.error(e);
    }
};

// 加载用户积分
fetch('http://your-backend-api/user/score')
   .then(res => res.json())
   .then(data => {
        userScore.value = data.score;
    });
</script>

3.3 后端实现

在 Spring Boot 后端,当接收到点赞请求时,除了更新点赞数据,还需要增加用户积分。在LikeServiceImpl中,修改like方法,增加积分处理逻辑。假设我们有一个UserScore表来存储用户积分,并且有一个UserScoreService来操作这个表。

@Service
public class LikeServiceImpl extends ServiceImpl<LikeMapper, Like> implements LikeService {
    @Autowired
    private UserScoreService userScoreService;

    @Override
    public void like(LikeDTO likeDTO) {
        QueryWrapper<Like> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", likeDTO.getUserId());
        wrapper.eq("target_id", likeDTO.getTargetId());
        Like like = this.getOne(wrapper);
        if (like == null) {
            like = new Like();
            like.setUserId(likeDTO.getUserId());
            like.setTargetId(likeDTO.getTargetId());
            like.setLike(likeDTO.getLike());
            this.save(like);
        } else {
            like.setLike(likeDTO.getLike());
            this.updateById(like);
        }

        // 增加点赞者积分
        UserScore userScore = userScoreService.getById(likeDTO.getUserId());
        if (userScore == null) {
            userScore = new UserScore();
            userScore.setUserId(likeDTO.getUserId());
            userScore.setScore(10); // 初始积分,假设点赞一次得10分
        } else {
            userScore.setScore(userScore.getScore() + 10);
        }
        userScoreService.saveOrUpdate(userScore);

        // 增加被点赞者积分
        UserScore targetUserScore = userScoreService.getById(likeDTO.getTargetId());
        if (targetUserScore == null) {
            targetUserScore = new UserScore();
            targetUserScore.setUserId(likeDTO.getTargetId());
            targetUserScore.setScore(5); // 被点赞得5分
        } else {
            targetUserScore.setScore(targetUserScore.getScore() + 5);
        }
        userScoreService.saveOrUpdate(targetUserScore);
    }
}

3.4 代码示例

3.4.1 uniapp 前端代码示例

<template>
    <view>
        <text>我的积分: {{ userScore }}</text>
        <button @click="likeAndUpdateScore">点赞</button>
    </view>
</template>

<script>
export default {
    data() {
        return {
            userScore: 0
        };
    },
    methods: {
        async likeAndUpdateScore() {
            try {
                const res = await uni.request({
                    url: 'http://your-backend-api/like',
                    method: 'POST',
                    data: {
                        targetId: 1,
                        like: true
                    }
                });
                if (res.statusCode === 200) {
                    const newScore = res.data.score;
                    this.userScore = newScore;
                    uni.showToast({
                        title: '点赞成功,积分增加',
                        icon:'success'
                    });
                }
            } catch (e) {
                console.error(e);
            }
        }
    },
    onLoad() {
        uni.request({
            url: 'http://your-backend-api/user/score',
            method: 'GET',
            success: res => {
                if (res.statusCode === 200) {
                    this.userScore = res.data.score;
                }
            }
        });
    }
};
</script>

3.4.2 Element Plus 前端代码示例

<template>
    <el-container>
        <el-header>
            <span>我的积分: {{ userScore }}</span>
            <el-tooltip content="积分可用于兑换礼品和优惠券">
                <i class="el-icon-question"></i>
            </el-tooltip>
            <el-button @click="likeAndUpdateScore">点赞</el-button>
        </el-header>
        <el-main>
            <!-- 页面主要内容 -->
        </el-main>
    </el-container>
</template>

<script setup>
import { ref } from 'vue';

const userScore = ref(0);

const likeAndUpdateScore = async () => {
    try {
        const res = await fetch('http://your-backend-api/like', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                targetId: 1,
                like: true
            })
        });
        if (res.ok) {
            const data = await res.json();
            userScore.value = data.score;
            alert('点赞成功,积分增加');
        }
    } catch (e) {
        console.error(e);
    }
};

fetch('http://your-backend-api/user/score')
   .then(res => res.json())
   .then(data => {
        userScore.value = data.score;
    });
</script>

3.4.3 Spring Boot 后端代码示例

  • UserScore实体类
@Data
@TableName("user_score")
public class UserScore {
    @TableId(type = IdType.AUTO)
    private Long id;
    private Long userId;
    private Integer score;
}
  • UserScoreService接口
public interface UserScoreService extends IService<UserScore> {
}
  • UserScoreServiceImpl实现类
@Service
public class UserScoreServiceImpl extends ServiceImpl<UserScoreMapper, UserScore> implements UserScoreService {
}
  • LikeServiceImpl修改后的实现类
@Service
public class LikeServiceImpl extends ServiceImpl<LikeMapper, Like> implements LikeService {
    @Autowired
    private UserScoreService userScoreService;

    @Override
    public void like(LikeDTO likeDTO) {
        QueryWrapper<Like> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", likeDTO.getUserId());
        wrapper.eq("target_id", likeDTO.getTargetId());
        Like like = this.getOne(wrapper);
        if (like == null) {
            like = new Like();
            like.setUserId(likeDTO.getUserId());
            like.setTargetId(likeDTO.getTargetId());
            like.setLike(likeDTO.getLike());
            this.save(like);
        } else {
            like.setLike(likeDTO.getLike());
            this.updateById(like);
        }

        // 增加点赞者积分
        UserScore userScore = userScoreService.getById(likeDTO.getUserId());
        if (userScore == null) {
            userScore = new UserScore();
            userScore.setUserId(likeDTO.getUserId());
            userScore.setScore(10);
        } else {
            userScore.setScore(userScore.getScore() + 10);
        }
        userScoreService.saveOrUpdate(userScore);

        // 增加被点赞者积分
        UserScore targetUserScore = userScoreService.getById(likeDTO.getTargetId());
        if (targetUserScore == null) {
            targetUserScore = new UserScore();
            targetUserScore.setUserId(likeDTO.getTargetId());
            targetUserScore.setScore(5);
        } else {
            targetUserScore.setScore(targetUserScore.getScore() + 5);
        }
        userScoreService.saveOrUpdate(targetUserScore);
    }
}

四、总结

在当今竞争激烈的电商市场中,社交互动功能已成为商城提升用户体验和竞争力的关键因素。通过实现用户关注、点赞、评论以及设计合理的社交互动激励机制,我们能够增强用户之间的联系,提高用户参与度和忠诚度,从而带动商品的传播和销售。无论是移动前端的 uniapp,还是 PC 前端的 Element Plus,亦或是后端的 Spring Boot 结合 MyBatis-Plus,都为这些社交互动功能的实现提供了强大的技术支持。希望读者能够在实际项目中积极应用这些功能和技术,不断优化商城的社交体验,打造出独具特色和竞争力的电商平台。

你可能感兴趣的:(商城实战,商城实战,商城社交互动功能,活跃用户,uniapp,Element,Plus,SPringBoot)