vue中的编程式导航
除了使用 <router-link>
创建 a 标签来定义导航链接,我们还可以借助 router 的实例方法,通过编写代码来实现。
router.push()
router.push(location, onComplete?, onAbort?)
注意:在 Vue 实例内部,你可以通过 $router 访问路由实例。因此你可以调用 this.$router.push。
提供 onComplete
和 onAbort
回调作为第二个和第三个参数。这些回调将会在导航成功完成 (在所有的异步钩子被解析之后) 或终止 (导航到相同的路由、或在当前导航完成之前导航到另一个不同的路由) 的时候进行相应的调用。
示例:路由导航的创建
// 字符串
router.push('home')
// 对象
router.push({ path: 'home' })
// 命名的路由
router.push({ name: 'user', params: { userId: 123 }})
// 带查询参数,变成 /register?plan=private
router.push({ path: 'register', query: { plan: 'private' }})
通过this.$route.query; // 获取
实例:
<body>
<div id="app">
<!-- 路由的入口和出口 -->
<!-- 路由的入口常规是链接导航 -->
<router-link to="/home">首页</router-link>
<!-- 编程导航方式1 -->
<button @click="goAbout">关于</button>
<!-- 编程导航方式2 -->
<button @click="goNews">新闻</button>
<!-- 路由出口 -->
<router-view></router-view>
</div>
<script src="./vue.js"></script>
<script src="./node_modules/vue-router/dist/vue-router.js"></script>
<script>
// 创建两个组件
const Home = Vue.component('home', {
template: `<h1>这是 Home 组件</h1>`
})
const About = Vue.component('about', {
template: `<h1>这是 About 组件</h1>`
})
const News = Vue.component('news', {
template: `<h1>这是 新闻 组件</h1>`
})
// 配置路由规则
const router = new VueRouter({
routes: [
{ path: '/home', component: Home },
{ path: '/about', component: About },
{ path: '/news', component: News, name:'news' }
]
})
var vm = new Vue({
el: '#app',
router,
methods:{
goAbout:function(){
// 编程导航方式1:使用$router.push(参数1) 中传递路径即可
this.$router.push({path: '/about'})
// 如果需要传参方式如下:
// this.$router.push({ path: `/home/photoinfo/${id}` })
},
goNews:function(){
// 编程导航方式2:使用$router.push({name:''}),路由导航中需要添加name名称
// this.$router.push({name:'news'})
// 如果需要传参方式如下:params参数
// this.$router.push({ name: 'photoinfo', params: { id } })
}
}
})
</script>
</body>
router.replace()
跟 router.push
很像,唯一的不同就是,它不会向 history 添加新记录,而是跟它的方法名一样 —— 替换掉当前的 history 记录。
声明式 | 编程式 |
---|---|
<router-link :to="..." replace> | router.replace(...) |
拼接path+data内的变量数据
<router-link :to="{path: '/' + slideOneImg.url}"></router-link>
router.go()
这个方法的参数是一个整数,意思是在 history 记录中向前或者后退多少步,类似 window.history.go(n)
。
例子
// 在浏览器记录中前进一步,等同于 history.forward()
router.go(1)
// 后退一步记录,等同于 history.back()
router.go(-1)
// 前进 3 步记录
router.go(3)
// 如果 history 记录不够用,那就默默地失败呗
router.go(-100)
router.go(100)