uni-app 收藏系统

核心知识点

1. 收藏系统架构

  • 前端组件:收藏按钮、收藏列表、收藏状态管理
  • 数据存储:本地存储、云端存储、数据同步
  • API 接口:收藏/取消收藏、获取收藏列表、收藏状态检查
  • 用户体验:收藏动画、状态反馈、批量操作

2. 收藏功能实现

  • 收藏状态管理:使用 Vuex 管理全局收藏状态
  • 收藏操作:单个收藏、批量收藏、取消收藏
  • 收藏计数:实时更新收藏数量
  • 收藏权限:用户登录状态检查

3. 数据存储策略

  • 本地存储:使用 uni.setStorageSync 缓存收藏状态
  • 云端存储:通过 API 同步到后端数据库
  • 数据同步:离线操作、网络恢复后同步
  • 数据一致性:解决多端数据同步冲突

4. 收藏列表管理

  • 列表展示:分页加载、下拉刷新、上拉加载
  • 分类管理:按时间、类型、来源分类
  • 搜索功能:快速查找收藏内容
  • 批量操作:批量删除、批量移动分类

5. 性能优化

  • 缓存策略:减少重复请求
  • 批量操作:合并 API 调用
  • 虚拟列表:优化长列表渲染
  • 本地缓存:减少网络依赖

实用案例

实现内容收藏功能

1. 收藏按钮组件

<template>
  <view class="favorite-btn" @click="toggleFavorite">
    <uni-icons 
      :type="isFavorite ? 'star-filled' : 'star'" 
      :size="size" 
      :color="isFavorite ? '#FFD700' : '#999'"
      class="favorite-icon"
    />
    <text v-if="showCount" class="favorite-count">{{ count }}</text>
  </view>
</template>

<script>
export default {
  props: {
    id: {
      type: [String, Number],
      required: true
    },
    type: {
      type: String,
      default: 'article'
    },
    size: {
      type: Number,
      default: 24
    },
    showCount: {
      type: Boolean,
      default: false
    },
    count: {
      type: Number,
      default: 0
    }
  },
  computed: {
    isFavorite() {
      return this.$store.getters['favorite/isFavorited']({
        id: this.id,
        type: this.type
      });
    }
  },
  methods: {
    toggleFavorite() {
      // 检查用户登录状态
      if (!this.$store.state.user.isLoggedIn) {
        uni.showToast({
          title: '请先登录',
          icon: 'none'
        });
        return;
      }
      
      this.$store.dispatch('favorite/toggleFavorite', {
        id: this.id,
        type: this.type
      });
    }
  }
};
</script>

<style scoped>
.favorite-btn {
  display: flex;
  align-items: center;
  gap: 8rpx;
}

.favorite-icon {
  transition: all 0.3s ease;
}

.favorite-count {
  font-size: 24rpx;
  color: #666;
}
</style>

2. Vuex 收藏模块

// store/modules/favorite.js
import favoriteApi from '@/api/favorite';

export default {
  namespaced: true,
  state: {
    favorites: [],
    loading: false,
    syncing: false
  },
  mutations: {
    SET_FAVORITES(state, favorites) {
      state.favorites = favorites;
    },
    ADD_FAVORITE(state, favorite) {
      const index = state.favorites.findIndex(
        item => item.id === favorite.id && item.type === favorite.type
      );
      if (index === -1) {
        state.favorites.unshift(favorite);
      }
    },
    REMOVE_FAVORITE(state, { id, type }) {
      state.favorites = state.favorites.filter(
        item => !(item.id === id && item.type === type)
      );
    },
    SET_LOADING(state, loading) {
      state.loading = loading;
    },
    SET_SYNCING(state, syncing) {
      state.syncing = syncing;
    }
  },
  actions: {
    // 初始化收藏数据
    async initFavorites({ commit, rootState }) {
      if (!rootState.user.isLoggedIn) return;
      
      commit('SET_LOADING', true);
      try {
        // 先从本地缓存加载
        const localFavorites = uni.getStorageSync('favorites');
        if (localFavorites) {
          commit('SET_FAVORITES', localFavorites);
        }
        
        // 再从服务器同步
        const res = await favoriteApi.getFavorites();
        if (res.success) {
          commit('SET_FAVORITES', res.data);
          // 更新本地缓存
          uni.setStorageSync('favorites', res.data);
        }
      } catch (error) {
        console.error('初始化收藏数据失败:', error);
      } finally {
        commit('SET_LOADING', false);
      }
    },
    
    // 切换收藏状态
    async toggleFavorite({ commit, state, rootState }, { id, type }) {
      if (!rootState.user.isLoggedIn) return;
      
      const isFavorited = state.favorites.some(
        item => item.id === id && item.type === type
      );
      
      try {
        if (isFavorited) {
          // 取消收藏
          await favoriteApi.unfavorite(id, type);
          commit('REMOVE_FAVORITE', { id, type });
        } else {
          // 添加收藏
          const res = await favoriteApi.favorite(id, type);
          if (res.success) {
            commit('ADD_FAVORITE', {
              id,
              type,
              createdAt: new Date().toISOString()
            });
          }
        }
        
        // 更新本地缓存
        uni.setStorageSync('favorites', state.favorites);
      } catch (error) {
        console.error('切换收藏状态失败:', error);
        // 网络错误时,使用本地操作
        if (isFavorited) {
          commit('REMOVE_FAVORITE', { id, type });
        } else {
          commit('ADD_FAVORITE', {
            id,
            type,
            createdAt: new Date().toISOString(),
            syncStatus: 'pending'
          });
        }
        uni.setStorageSync('favorites', state.favorites);
        // 记录离线操作,网络恢复后同步
        uni.setStorageSync('offlineFavorites', {
          ...uni.getStorageSync('offlineFavorites'),
          [`${type}_${id}`]: !isFavorited
        });
      }
    },
    
    // 同步离线操作
    async syncOfflineFavorites({ commit, state }) {
      const offlineOperations = uni.getStorageSync('offlineFavorites');
      if (!offlineOperations) return;
      
      commit('SET_SYNCING', true);
      try {
        for (const [key, shouldFavorite] of Object.entries(offlineOperations)) {
          const [type, id] = key.split('_');
          if (shouldFavorite) {
            await favoriteApi.favorite(id, type);
          } else {
            await favoriteApi.unfavorite(id, type);
          }
        }
        // 清空离线操作记录
        uni.removeStorageSync('offlineFavorites');
        
        // 重新获取最新数据
        const res = await favoriteApi.getFavorites();
        if (res.success) {
          commit('SET_FAVORITES', res.data);
          uni.setStorageSync('favorites', res.data);
        }
      } catch (error) {
        console.error('同步离线操作失败:', error);
      } finally {
        commit('SET_SYNCING', false);
      }
    }
  },
  getters: {
    isFavorited: (state) => ({ id, type }) => {
      return state.favorites.some(item => item.id === id && item.type === type);
    },
    favoriteCount: (state) => (type) => {
      if (type) {
        return state.favorites.filter(item => item.type === type).length;
      }
      return state.favorites.length;
    },
    getFavoritesByType: (state) => (type) => {
      return state.favorites.filter(item => item.type === type);
    }
  }
};

3. 收藏 API 服务

// api/favorite.js
import request from './request';

export default {
  // 添加收藏
  async favorite(id, type) {
    return request({
      url: '/api/favorite/add',
      method: 'POST',
      data: {
        targetId: id,
        targetType: type
      }
    });
  },
  
  // 取消收藏
  async unfavorite(id, type) {
    return request({
      url: '/api/favorite/remove',
      method: 'POST',
      data: {
        targetId: id,
        targetType: type
      }
    });
  },
  
  // 获取收藏列表
  async getFavorites(params = {}) {
    return request({
      url: '/api/favorite/list',
      method: 'GET',
      params
    });
  },
  
  // 检查收藏状态
  async checkFavorite(id, type) {
    return request({
      url: '/api/favorite/check',
      method: 'GET',
      params: {
        targetId: id,
        targetType: type
      }
    });
  },
  
  // 批量操作
  async batchOperation(operation, items) {
    return request({
      url: '/api/favorite/batch',
      method: 'POST',
      data: {
        operation,
        items
      }
    });
  }
};

4. 收藏列表页面

<template>
  <view class="favorite-list">
    <view class="list-header">
      <text class="title">我的收藏</text>
      <uni-badge :text="totalCount" type="error" class="badge" />
    </view>
    
    <view class="filter-bar">
      <uni-segmented-control 
        :values="['全部', '文章', '商品', '视频']" 
        :current="activeTypeIndex"
        @clickItem="handleTypeChange"
        style-type="button"
        active-color="#007AFF"
      />
    </view>
    
    <uni-refresher 
      v-model="refreshing" 
      @refresh="onRefresh"
      :contentdown="{ content: '下拉刷新' }"
      :contentover="{ content: '释放刷新' }"
      :contentrefresh="{ content: '刷新中...' }"
    >
      <uni-list v-if="filteredFavorites.length > 0">
        <uni-list-item 
          v-for="(item, index) in filteredFavorites" 
          :key="`${item.type}_${item.id}`"
          :title="getItemTitle(item)"
          :thumb="getItemThumb(item)"
          :note="formatDate(item.createdAt)"
          show-arrow
          @click="navigateToDetail(item)"
          class="list-item"
        >
          <view slot="extra" class="item-actions">
            <uni-icons 
              type="trash" 
              size="20" 
              color="#FF3B30" 
              @click.stop="removeFavorite(item)"
            />
          </view>
        </uni-list-item>
      </uni-list>
      
      <view v-else class="empty-state">
        <uni-icons type="star" size="60" color="#CCCCCC" />
        <text class="empty-text">暂无收藏内容</text>
      </view>
    </uni-refresher>
    
    <uni-load-more 
      :status="loadStatus" 
      :loading-text="'加载中...'" 
      :no-more-text="'没有更多了'" 
      :fail-text="'加载失败'"
      @clickLoadMore="loadMore"
      v-if="filteredFavorites.length > 0"
    />
  </view>
</template>

<script>
export default {
  data() {
    return {
      activeTypeIndex: 0,
      types: ['all', 'article', 'product', 'video'],
      refreshing: false,
      loadStatus: 'more',
      page: 1,
      pageSize: 10,
      hasMore: true
    };
  },
  computed: {
    totalCount() {
      return this.$store.getters['favorite/favoriteCount']();
    },
    filteredFavorites() {
      const currentType = this.types[this.activeTypeIndex];
      if (currentType === 'all') {
        return this.$store.state.favorite.favorites;
      }
      return this.$store.getters['favorite/getFavoritesByType'](currentType);
    }
  },
  onLoad() {
    this.initData();
  },
  methods: {
    initData() {
      this.$store.dispatch('favorite/initFavorites');
    },
    
    handleTypeChange(e) {
      this.activeTypeIndex = e.current;
      this.page = 1;
      this.hasMore = true;
    },
    
    onRefresh() {
      this.refreshing = true;
      this.page = 1;
      this.$store.dispatch('favorite/initFavorites').finally(() => {
        this.refreshing = false;
      });
    },
    
    loadMore() {
      if (this.loadStatus === 'loading' || !this.hasMore) return;
      
      this.loadStatus = 'loading';
      // 实际项目中这里应该调用分页加载 API
      setTimeout(() => {
        this.loadStatus = 'noMore';
        this.hasMore = false;
      }, 1000);
    },
    
    removeFavorite(item) {
      uni.showModal({
        title: '确认删除',
        content: '确定要删除这条收藏吗?',
        success: (res) => {
          if (res.confirm) {
            this.$store.dispatch('favorite/toggleFavorite', {
              id: item.id,
              type: item.type
            });
          }
        }
      });
    },
    
    navigateToDetail(item) {
      // 根据不同类型跳转到对应详情页
      switch (item.type) {
        case 'article':
          uni.navigateTo({ url: `/pages/article/detail?id=${item.id}` });
          break;
        case 'product':
          uni.navigateTo({ url: `/pages/product/detail?id=${item.id}` });
          break;
        case 'video':
          uni.navigateTo({ url: `/pages/video/detail?id=${item.id}` });
          break;
      }
    },
    
    getItemTitle(item) {
      // 实际项目中应该根据 item 数据返回对应的标题
      return `${item.type} - ${item.id}`;
    },
    
    getItemThumb(item) {
      // 实际项目中应该返回对应的缩略图
      return '';
    },
    
    formatDate(dateString) {
      const date = new Date(dateString);
      return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
    }
  }
};
</script>

<style scoped>
.favorite-list {
  padding: 20rpx;
  min-height: 100vh;
  background-color: #F5F5F5;
}

.list-header {
  display: flex;
  align-items: center;
  margin-bottom: 20rpx;
}

.title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.badge {
  margin-left: 10rpx;
}

.filter-bar {
  margin-bottom: 20rpx;
  background-color: #FFFFFF;
  border-radius: 8rpx;
  padding: 10rpx;
}

.list-item {
  margin-bottom: 10rpx;
  background-color: #FFFFFF;
  border-radius: 8rpx;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 0;
  color: #999;
}

.empty-text {
  margin-top: 20rpx;
  font-size: 28rpx;
}
</style>

实用技巧

1. 离线收藏功能

  • 本地存储:使用 uni.setStorageSync 存储收藏状态
  • 离线操作:记录用户的离线收藏操作
  • 网络恢复:监听网络状态变化,自动同步离线操作
  • 冲突处理:解决多端操作导致的数据冲突

2. 性能优化策略

  • 防抖处理:避免频繁点击导致的重复请求
  • 批量操作:合并多个收藏/取消收藏请求
  • 缓存策略:缓存收藏状态,减少 API 调用
  • 虚拟列表:使用虚拟滚动优化长列表性能

3. 用户体验提升

  • 收藏动画:添加收藏/取消收藏的动画效果
  • 批量管理:支持多选、批量删除等操作
  • 智能分类:自动按类型、时间等维度分类
  • 快速访问:提供常用收藏的快捷入口

4. 安全考虑

  • 权限检查:确保用户登录后才能收藏
  • 防刷机制:限制收藏操作频率
  • 数据验证:后端验证收藏数据的合法性
  • 隐私保护:保护用户的收藏隐私

总结

通过本教程的学习,你已经掌握了 uni-app 收藏系统的完整实现方法,包括:

  1. 收藏系统架构设计:了解了收藏系统的前端组件、数据存储、API 接口等核心组成部分

  2. 收藏功能实现:掌握了收藏状态管理、收藏操作、数据存储等核心功能的实现

  3. 收藏列表管理:学会了如何构建收藏列表页面,包括分类筛选、下拉刷新、上拉加载等功能

  4. 离线同步机制:实现了离线收藏功能,确保网络不稳定时用户体验不受影响

  5. 性能优化策略:应用了多种性能优化技巧,提升了收藏系统的响应速度和稳定性

  6. 用户体验提升:通过动画效果、批量操作等功能,提升了用户体验

收藏系统是许多应用的核心功能之一,它不仅可以提高用户粘性,还能为用户提供个性化的内容管理体验。在实际项目中,你可以根据具体需求对本教程中的实现进行扩展和优化,构建更加完善的收藏系统。

学习目标

  • 掌握 uni-app 收藏系统的完整实现方法
  • 理解收藏系统的架构设计和数据流程
  • 学会使用 Vuex 管理全局收藏状态
  • 掌握本地存储和云端存储的结合使用
  • 实现离线收藏和数据同步功能
  • 应用性能优化策略提升系统响应速度
  • 设计良好的用户体验,包括动画效果和批量操作

通过本教程的学习,你已经具备了开发高质量收藏系统的能力,可以在实际项目中灵活应用这些知识,为用户提供更好的内容管理体验。

« 上一篇 uni-app 点赞系统 下一篇 » uni-app 搜索系统