# 点赞与收藏

# 技术点

颗粒化组件 注册全局组件

# 1 目录结构

└─ components                
   └─ tool            
      ├─ user-collection      # 用户收藏
      └─ user-like            # 用户点赞

# 2 使用地方

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

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

# 3 组件详解

以下以点赞组件为例

<view class="tool-item tool-item-class {{ data.allow_like ? 'is-disabled': '' }}" bindtap="likeClick">
	<view class="tool-item-icon {{ data.is_like ? 'is-checked' : '' }}">
		<c-icon class="icon" name="like-fill" />
	</view>
	<view class="tool-item-count">{{ data.like_count || defaultCount }}</view>
</view>
// 引入点赞与取消点赞按钮
import { createLike, deleteLike } from "../../../api/user";

Component({
  properties: {
    type: {
      type: String,
      required: true,
    },
    // 数据
    data: {
      type: Object,
      required: true,
    },
    defaultCount: {
      value: "喜欢",
      type: String
    },
  },

  data: {
    loading: false
  },

  methods: {
    async likeClick() {
      if (this.data.data.allow_like === 0) return;

      if (this.data.loading) return;

      this.setData({
        loading: true
      })

      const { code, data } = this.data.data.is_like ?
        await deleteLike(this.data.type, this.data.data.id) :
        await createLike(this.data.type, this.data.data.id);

      this.setData({
        loading: false
      })

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

# 组件注册

"usingComponents": {
	"user-like": "components/tool/user-like"
}

# 组件使用

<!-- type 为资源类型 -->
<!-- data 为资源详情 -->
<user-like type="{{type}}" data="{{data}}" />
上次更新: 2022-10-25 9:05:36 ├F10: PM┤