# 点赞与收藏

# 技术点

颗粒化组件 注册全局组件

# 1 目录结构

└─ src                          
   └─ components                
      └─ Tool            
         ├─ UserCollection      # 用户收藏
         └─ UserLike            # 用户点赞

# 2 使用地方

评论的点赞功能未使用该组件,因为评论点赞的数据量后期会很大,所以单独设计。

主要使用在 review, article, video 等组件中。

# 3 组件详解

以下以点赞组件为例

<div
    class="tool-item"
    :class="{ 'is-disabled': data.allow_like }"
    @click="likeClick()"
>
    <div class="tool-item-icon" :class="{ 'is-checked': data.is_like }">
        <!-- 点赞图标 -->
        <i class="m-icon m-icon-like-fill"></i>
    </div>
    <!-- 点赞数量 -->
    <div class="tool-item-count">{{ data.like_count || defaultCount }}</div>
</div>
// 引入点赞与取消点赞按钮
import { createLike, deleteLike } from "@/api/user";

export default {
    name: "UserLike",

    props: {
        // 资源类型,支持 photos、articles、videos等
        type: {
            required: true,
            type: String,
        },
        // 点赞数据
        data: {
            required: true,
            type: Object,
        },
        // 点赞数量默认值,如无点赞,则显示"喜欢"
        defaultCount: {
            default: "喜欢",
        },
    },

    methods: {
        async likeClick() {
        // 不允许点赞
            if (this.data.allow_like === 0) {
                return;
            }

            // 已经发起点赞或取消点赞时,不可重复发起请求
            if (this.loading) return;

            this.loading = true;
            let { code, data } = this.data.is_like
                ? await deleteLike(this.type, this.data.id)
                : await createLike(this.type, this.data.id);
            this.loading = false;

            if (code === 200) {
                // this.$emit("on-change", data);
                Object.assign(this.data, data);
            }
        },
    },
};

# 组件注册

main.js 中,引入并注册该组件

import UserLike from "./components/Tool/UserLike/index";
Vue.use(UserLike);

# 组件使用

<!-- 以照片点赞为例 -->
<user-like type="photos" :data="photo" default-count="" />
上次更新: 6/24/2022, 6:15:24 PM
示例展示,因PC端无touch事件,请在手机上进行浏览