下面的第一种方法以前有用,今天(2020/1/13)写项目时发现无效了,找到了第二种方法,写在最后
第一种方法:
- 判断当前页面的历史记录是不是小于等于1,如果小于等于1,说明这个页面没有可以返回的上一页,如果没有可以返回的上一页,就给地址栏加上一个goindex=true的参数,这样你从这个页面再往下一个页面跳转再返回,这个参数会一直在你刚进去的那个页面的url上.
// main.js中
Vue.prototype.$setgoindex = function () { // 给初始进入的页面加上goindex参数
if (window.history.length <= 1) {
if (location.href.indexOf('?') === -1) {
window.location.href = location.href + '?goindex=true'
} else if (location.href.indexOf('?') !== -1 && location.href.indexOf('goindex') === -1) {
window.location.href = location.href + '&goindex=true'
}
}
}
Vue.prototype.goBack = function () { // 点击返回按钮处罚的事件
if (this.$route.query.goindex === 'true') {
this.$router.push('/')
} else {
this.$router.back(-1)
}
}
- 在入口组件中,挂载全局方法
// APP.vue中
mounted(){
this.$setgoindex();
}
// 若加了kepp-alive缓存,也可以在activated中挂载
activated(){
this.$setgoindex();
}
- 在有返回按钮的页面的methods中定义返回按钮的点击事件pushBack:
// 在有返回按钮的页面
pushBack() {
this.goBack();
}
参考: https://segmentfault.com/q/1010000010714863
第二种方法:
- 在script标签内定义变量hasPath(随便命名)
<script>
let hasPath;
export default {
....
}
</script>
- 使用组件内函数,beforeRouteEnter,直接来获取form.path(即为对应的上一次地址的路由path内容);如果无路由历史,会返回: '/'
beforeRouteEnter(to, from, next) {
hasPath = from.path;
console.log(hasPath); // 返回: ' / '
next()
}
- 点击返回键处理返回逻辑,返回到自己想要返回的页面
methods: {
onBack(){
if ( hasPath == '/' ) {
this.$router.push('/home'); // 这里我返回到home首页
return;
}
this.$router.go(-1);
}
}