uni-app 插件市场希望增加单个插件收藏入口 方便用户日后使用而不立即下载

发布于 1周前 作者 wuwangju 来自 Uni-App

uni-app 插件市场希望增加单个插件收藏入口 方便用户日后使用而不立即下载

1 回复

理解你的需求,为了在 uni-app 插件市场中增加单个插件的收藏入口,我们可以通过以下方式实现。这通常涉及到前端和后端的协作,但为了简洁起见,这里主要展示前端代码示例,假设后端已经提供了收藏相关的API接口。

前端实现(以Vue.js为例)

  1. 模板部分(Template)

在插件详情页面添加一个收藏按钮:

<template>
  <div class="plugin-detail">
    <!-- 插件详情内容 -->
    <button @click="toggleFavorite" :class="{ active: isFavorite }">
      <span v-if="isFavorite">已收藏</span>
      <span v-else>收藏</span>
    </button>
  </div>
</template>
  1. 脚本部分(Script)

在Vue组件的脚本部分,定义相关的数据和方法:

<script>
export default {
  data() {
    return {
      isFavorite: false, // 初始状态为未收藏
      pluginId: 123, // 假设当前插件的ID为123
    };
  },
  methods: {
    async toggleFavorite() {
      try {
        const response = await fetch(`/api/plugins/${this.pluginId}/favorite`, {
          method: this.isFavorite ? 'DELETE' : 'POST',
          headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${localStorage.getItem('token')}` // 假设使用JWT认证
          },
        });
        const result = await response.json();
        if (result.success) {
          this.isFavorite = !this.isFavorite;
        } else {
          // 处理错误
          console.error('收藏失败:', result.message);
        }
      } catch (error) {
        console.error('请求错误:', error);
      }
    },
  },
  async created() {
    try {
      const response = await fetch(`/api/plugins/${this.pluginId}/favorite-status`, {
        method: 'GET',
        headers: {
          'Authorization': `Bearer ${localStorage.getItem('token')}`
        },
      });
      const result = await response.json();
      if (result.isFavorite) {
        this.isFavorite = true;
      }
    } catch (error) {
      console.error('获取收藏状态失败:', error);
    }
  },
};
</script>
  1. 样式部分(Style)

为收藏按钮添加一些基本样式:

<style scoped>
button {
  background-color: #007bff;
  color: white;
  border: none;
  padding: 10px 20px;
  cursor: pointer;
}
button.active {
  background-color: #28a745;
}
</style>

总结

上述代码展示了如何在uni-app插件详情页增加一个收藏按钮,并通过点击事件来切换插件的收藏状态。这里假设后端提供了/api/plugins/:id/favorite用于收藏/取消收藏,以及/api/plugins/:id/favorite-status用于获取当前插件的收藏状态。实际开发中,你需要根据后端API的具体实现来调整请求URL和请求体。

回到顶部