标签页面-选项卡业务逻辑处理
# 标签页面-选项卡业务逻辑处理
# 一、创建我的标签及推荐标签数组
使用计算属性进行数组创建
selfLabelList () { return this.labelList.filter(item => this.labelIds.includes(item._id)) }, recommentLabelList () { return this.labelList.filter(item => !this.labelIds.includes(item._id) && item._id) },初始化定义本地数据对象
为了不影响用户数据,页面内定义属性进行用户数组信息数据拷贝,watch中进行调用,为了防止用户在修改之后,进行用户的改变无法获取准确的内容,通过watch中进行拷贝操作,并使用immediate初始话进行watch使用
watch: { userInfo: { immediate: true, handler (newVal, oldVal) { this.labelIds = [...(this.userInfo.label_ids)] } } },进行页面数据渲染
// 用户标签组 <view class="label-content-item" v-for="(item,index) in selfLabelList" :key="index"> {{item.name}} <uni-icons @click="deleteLabelItem(item)" v-if="isEdit" class="icon-close" type="clear" size="20" color="red"></uni-icons> </view> <view v-if="!selfLabelList.length" class="no-data">当前没有数据</view> </view> // 推荐标签组 <view class="label-content"> <view class="label-content-item" @click="changeSelfList(item)" v-for="(item,index) in recommentLabelList" :key="index"> {{item.name}} </view> <view v-if="!recommentLabelList.length" class="no-data">当前没有数据</view> </view>为标签切换添加点击事件
标签切换过程中需要注意,在isEdit情况下在进行标签切换操作。,追加用户标签,直接修改labelIds,删除标签,直过滤匹配内容。在未点击保存按钮的时候,不需要进行振正数据存储
//修改当前用户的labelList changeSelfList (item) { if (!this.isEdit) return this.labelIds.push(item._id) }, // 删除用户选项内容 deleteLabelItem (item) { this.labelIds = this.labelIds.filter(val => val !== item._id) }
# 二、数据发送
前端收集数据,当前用户ID,及现阶段收藏的数组 selfIds
const label_ids = this.selfLabelList.map(item => item._id) const res = await this.$http.update_label_ids({ userId: this.userInfo._id, label_ids });创建云函数。修改数据库中用户label_ids字段
'use strict'; const db = uniCloud.database() exports.main = async (event, context) => { //event为客户端上传的参数 const {userId,label_ids} = event const res = await db.collection('user').doc(userId).update({ label_ids }) //返回数据给客户端 return { code:0, data:{ msg:"修改成功" } } };前端接收返回值,重新调整userInfo即可。
uni.showToast({ title: res.msg }) this.updateUserInfo({ ...this.userInfo, label_ids });
# 三、处理其他界面副作用
调整index界面labelList获取方式,判断是否包含用户信息,不包含直接返回,否则,显示用户搜藏内容
computed: { labelList () { if (this.userInfo) { this.activeIndex = 0; return [...this.$store.state.labelList.slice(0,1),...this.$store.state.labelList.filter(item => this.userInfo.label_ids.includes(item._id))] } else { return this.$store.state.labelList } },article页面内部兼听到userList改变值后,清空列表对象
watch: { labelList (newVal, OldVal) { this.articleData = {} this.loadData = {} this._getArticleList(this.activeIndex) }, },