1. router----index.js
//解决跳转不让重定向问题
const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push(location, onResolve, onReject) {
if (onResolve || onReject)
return originalPush.call(this, location, onResolve, onReject);
return originalPush.call(this, location).catch((err) => err);
};
// 路由前置守卫
router.beforeEach((to, from, next) => {
// console.log(to.path);
if (["/cart", "/order","/mine"].indexOf(to.path) != -1) {
//判断用户是否登录
const token = localStorage.getItem("token");
if (token) next();
else next(`/login?target=${to.path}`);
} else {
next();
}
});
2. login.vue
methods: {
//点击提交
onSubmit(values) {
fetch("https://v5.crmeb.net/api/login",{
method:"POST",
headers:{
"Content-Type": "application/json",
},
body: JSON.stringify({
account:values.acc,
password:values.pwd,
}),
})
.then(resp=>resp.json())
.then(({data})=>{
// console.log(data);
localStorage.setItem("token",data.token);
this.$router.replace(this.$route.query.target);
});
},
},