Vue中使用VueCookies将收藏植物ID以数组形式存入Cookie的方法
修改方案
你需要在收藏按钮的点击事件里先读取现有收藏数据,处理后再保存,而非直接覆盖原有值。以下是具体实现方式:
核心处理逻辑
- 读取Cookie中已有的收藏ID字符串
- 将字符串转为数组(无数据则初始化为空数组)
- 校验新ID是否已存在(避免重复收藏)
- 将新ID加入数组后,转回逗号分隔的字符串存回Cookie
具体代码示例
假设你的收藏点击事件函数是handleCollect(plantId),修改后代码如下:
handleCollect(plantId) { // 读取现有收藏数据,默认空字符串 let favoriteIds = this.$cookies.get('favoritePlants') || ''; // 转换为数组,空字符串直接转成空数组 let idArray = favoriteIds ? favoriteIds.split(',') : []; // 检查是否已收藏,避免重复添加 if (!idArray.includes(plantId)) { idArray.push(plantId); // 把数组转回逗号分隔的字符串,存回Cookie this.$cookies.set('favoritePlants', idArray.join(',')); console.log('收藏成功'); } else { console.log('该植物已在收藏列表中'); } }
可选:支持取消收藏
如果需要点击按钮切换收藏/取消状态,可以在ID已存在时移除该ID,再更新Cookie:
handleCollect(plantId) { let favoriteIds = this.$cookies.get('favoritePlants') || ''; let idArray = favoriteIds ? favoriteIds.split(',') : []; if (idArray.includes(plantId)) { // 取消收藏:过滤掉当前ID idArray = idArray.filter(id => id !== plantId); this.$cookies.set('favoritePlants', idArray.join(',')); console.log('取消收藏成功'); } else { // 添加收藏 idArray.push(plantId); this.$cookies.set('favoritePlants', idArray.join(',')); console.log('收藏成功'); } }
这样就能实现每次点击时将新ID追加到现有收藏列表,而非直接覆盖原有数据。
内容的提问来源于stack exchange,提问作者cherno304
相关产品推荐
相关产品推荐

