一、需求
功能描述
商品详情页中点击立即收藏,通过调用后台接口将商品添加到收藏表,添加后按钮变为取消收藏;点击取消收藏,调用后台接口将商品从数据库中删除,随后按钮恢复为立即收藏;
实现思路
用户登录后进入从商城首页点击进入商品详情页面或刷新商品详情页面,通过获取当前登录人id和当前商品id(示例代码为车辆id,下面全部车辆由商品代替)到收藏表中查询收藏信息,若有数据则前台显示取消收藏,之后用户点击“立即收藏/取消收藏”,向后台发送请求操作数据库,并在前台页面提示操作结果,收藏按钮随之变换为“取消收藏/立即收藏”。
二、实现
代码实现
添加收藏按钮,使用@click设置点击事件,当点击时触发方法,使用条件表达式设置显示“立即收藏”或“取消收藏”。
<el-button class="appoint" @click="saveCollectInfo">{{ isCollected ? '取消收藏' : '立即收藏' }}</el-button>
isCollected初始值设置为false,表示为未收藏,不设置会报异常
添加saveCollectInfo方法
/**
*添加/取消收藏
*/
saveCollectInfo(){
let userInfo = this.$store.state.userInfo;
if (userInfo == null){
return this.$message.warning('请登录')
}
this.$confirm('确定要' + (this.isCollected ? '取消收藏' : '立即收藏') + '吗?', '提示', {
type: 'warning'
}).then(action => {
if (action === 'confirm') {
const params = {
userId: this.$store.state.userInfo.id,
carId: this.detailInfo.id,
};
saveCollectInfo(params).then(res=>{
if (res.code === 1){
this.$message.success(res.msg);
this.getData();
this.isCollected = !this.isCollected; //切换收藏状态
}else {
return this.$message.error(res.msg)
}
});
}
}).catch(() => {});
},
mounted()
生命周期钩子函数调用 this.checkCollectStatus()
方法。
在method中添加checkCollectStatus()
方法,在该方法中调用后台接口通过当前登录人id和商品id查询是否已经添加收藏。
checkCollectStatus(){
const params = {
user_id:sessionStorage.getItem('userId'),
car_id:this.$route.query.id,
};
getCollectStatus(params).then(res => {
console.log(res);
if(res === true){
//如果查询到结果,表示已经收藏
this.isCollected = true;
}else{
this.isCollected = false;
}
})
},
前台向后端发送请求,获取当前登录用户是否已经收藏当前商品。
/**
* 获取收藏状态
* @param query
* @returns {*}
*/
export const getCollectStatus = (query) => {
return request({
url: '/common/collect/getCollectStatus',
method: 'get',
params: query
});
};
这里使用的是后端返回的布尔值进行判断,如果为ture则代表已收藏,按钮变为取消收藏,反之则相反。当然也可以使用其他方法。
后台正常操作数据库查询数据判断是否收藏就很ez了,自行补充就好啦☺
实现效果
实现效果如下,立即收藏和取消收藏可以根据用户和商品之间的收藏状态自动变更。