文章详情-关注与取消关注-return Promise.reject(err)抛出错误,阻止程序运行
- 绑定事件
<van-button @click="toggleFollowing()" round size="small" type="info">
{{article.is_followed?'已关注':'+ 关注'}}
</van-button>
- 封装Api
src/api/user.js
/**
* 关注用户
* @param {Integer} userId
*/
export const following = (userId) => {
return request('app/v1_0/user/followings', 'post', {
target: userId
})
}
/**
* 取消关注用户
* @param {Integer} userId
*/
export const unFollowing = (userId) => {
// 拼接用户ID的写法
return request(`app/v1_0/user/followings/${userId}`, 'delete')
}
完成业务
src/views/home/article.vue中script里
// 引入api
import { following, unFollowing } from '@/api/user'
methods:{
// 添加关注 取消关注 自己不能关注自己
// ... 省略
async toggleFollowing () {
if (this.article.is_followed) {
// 取消关注
await unFollowing(this.article.aut_id)
// 处理成功 提示消息
// this.$toast.success('取消关注成功')
this.$toast({ type: 'success', message: '取消关注成功' })
// 修改数据状态
this.article.is_followed = false
} else {
// 添加关注
await following(this.article.aut_id)
// 处理成功 提示消息
this.$toast({ type: 'success', message: '添加关注成功' })
//修改数据状态
this.article.is_followed = true
}
},
}
查看src/utils/request.js中:
// TODO 处理token失效
//抛出错误,阻止程序运行
return Promise.reject(err)
注意:request.js 工具函数,修改目的,抛出错误阻碍程序运行。
跳转时,要注意除了跳转,还有-抛出错误,阻止程序运行;重新登录
//跳转登录的配置目的:将来需要传参query形式如果是vue组件 this.$route.path
//但是不是导入router实例--->router.currentRoute.path 当前页面的地址const login={path:‘/login',query:{redirect:router.currentRoute.path}}
//防止未登录必须有refresh_token
if(!user.token ll!user.refresh_token){
+outer.push(1ogin)
+return Promise.reject(err)
}
}catch(e){
//刷新token失败
//清理无效token
store.commit('deluser')
//跳转登录页面
+return router.push(login)
+return Promise.reject(err)
版权声明:本文为weixin_44867717原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。