前言
在用 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()
方法跳转其他路由