一次返回上级页面引发的问题的思考

前言

在用 vue 做 PC 项目时,有这么一个需要,从首页进入次级页面,然后点击次级页面的返回按钮返回首页。一个很简单的功能,用 Vue Router 的功能就可以实现。

环境

  • vue2.5
  • webpack3.6
  • element-ui2.6.1

有问题的效果

在这里插入图片描述
可以观察到,当进入 other 页面后,复制链接,重开一个窗口,通过 url 直接进入 other 页面,然后点击返回按钮,结果返回了空白页面,什么都没有,然而,我希望能返回首页。

Vue Router实现

Vue Router 中介绍中看到这么一个返回函数。

export default {
  methods: {
    goBack () {
      window.history.length > 1
        ? this.$router.go(-1)
        : this.$router.push('/')
    }
  }
}

代码实现

Home.vue

<template>
  <div>
    <el-button type="primary" @click="toOther">toOther</el-button>
  </div>
</template>

<script>
export default {
  methods: {
    toOther () {
      this.$router.push('/other')
    }
  }
}
</script>

Other.vue

<template>
  <section>
    <el-button @click="goBack">返回</el-button>
  </section>
</template>

<script>
export default {
  methods: {
    goBack () {
      window.history.length > 1
        ? this.$router.go(-1)
        : this.$router.push('/')
    }
  }
}
</script>

router.js

import Vue from 'vue'
import Router from 'vue-router'
import Home from '@/components/Home'
import Other from '@/components/Other'

Vue.use(Router)

export default new Router({
  routes: [
    {
      path: '/',
      name: 'Home',
      component: Home
    },
    {
      path: '/other',
      name: 'Other',
      component: Other
    }
  ]
})

有这么一个需求:
一个 PC 项目需要登录后才能进入首页,然则,在邮件的链接中进入项目的任一页面,可能是首页,可能是次级页面。次级页面可以返回上级页面,此时,浏览器的 history 仅仅只记录了当前页面,故此时返回上级页面即进入了浏览器的空白页面。
那么,此时就不能使用 this.$router.go(-1) 这个方法了,需要准确的用到路由定位页面。

修改 Other.vue ,使用路由的 path 返回首页
Other.vue

<template>
  <section>
    <el-button @click="goBack">返回</el-button>
  </section>
</template>

<script>
export default {
  methods: {
    goBack () {
      this.$router.push('/')
    }
  }
}
</script>

正确的效果

在这里插入图片描述

总结

尽量使用 this.$router.push() 方法跳转其他路由

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值