问题描述
有点像这样的代码:
if (**router.back.length == 0**){
router.push({name:"Home"})
}else {
router.back();
}
}
问题是我不知道如何判断 .back () 是否可行。
我目前在 pageNotFound,我使用以下重定向转到当前页面
path: "/:catchAll(.*)",name: "PageNotFound",component: () =>
import(/* webpackChunkName: "NotFound" */ "@/views/PageNotFound.vue")
}
感谢您的帮助!
解决方法
曾经有过类似的情况。尝试这样的事情(将其视为伪代码):
data: () => ({
fromRoute: null
}),beforeRouteEnter (to,from,next) {
next(vm => {
vm.fromRoute = from;
})
},methods: () {
handleBack() {
if (!this.fromRoute.name) {
router.push({name:"Home"});
} else {
router.back();
}
}
}
更多信息在这里:https://forum.vuejs.org/t/how-to-go-back-or-go-home/30242/3
,使用此代码来实现所需的结果。确保您使用的是 [Named Routes][1]
。
export default {
data() {
return {
fromRoute: null
};
},beforeRouteEnter(to,next) {
next((vm) => {
vm.fromRoute = from;
});
},methods: {
goBack() {
if (!this.fromRoute.name) {
this.$router.push("/");
} else {
this.$router.back();
}
},},};
[1]: https://router.vuejs.org/guide/essentials/named-routes.html
,
通过查看 VueJs 文档,我找到了解决方案
goBack() {
if(this.$router.getRoutes().length==0){
this.$router.push({name:"Home"})
}else{
this.$router.back();
}
}