除了使用<router-link>创建a标签来定义导航链接,我们还可以借助router的实例方法,通过编写代码来实现。 router.push(location) 想要导航到不同的url,则使用router.push方法。这个方法会像history栈添加一个新的记录, 所以,当用户点击浏览器后退按钮时,则回到之前的url 当你点击<router-link>时,这个方法会在内部调用,所以说,点击<router-link :to="...">等同于调用 router.push(...) 该方法的参数可以是一个字符串路径,或者一个描述地址的对象,例如: //字符串 router.push("home") //对象 router.push({path:"home"}) 命名的路由 router.push({name:"user",params:{userId:123}}) //带查询参数,变成/register?plan=private router.push({path:'register',query:{plan:'private'}})
router.replace(location) 跟router.push很像,唯一不同就是,它不会像history添加新记录,而是跟它的方法名一样-替换掉当前的history记录 声明<router-link :to="..." replace> 编程式 router.replace(...)
router.go(n) 这个方法的参数是一个整数,意思是在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)
一个简单的例子
<body class="">
<script src="../js/vue.js"></script>
<script src="../js/vue-router.js"></script>
<div id="app">
<button v-on:click="showHome">显示home</button>
<button v-on:click="showOther">显示其他</button>
<router-view></router-view>
</div>
<script>
const Home = {
template: `<div>this is the home page</div>`
}
const Other = {
template: `<div>this is the other page</div>`
}
const router = new VueRouter({
routes: [
{ path: "/home", component: Home },
{ path: "/other", component: Other },
]
})
var app = new Vue({
el: "#app",
router: router,
methods: {
showHome: function() {
this.$router.push({ path: '/home' })
},
showOther: function() {
this.$router.push({ path: '/other' })
},
}
})
//router.push({ path: '/home' }) 类似所有出现的/ 不能省略
//this.$router.push({ path: '/home' }) 也可以写成router.push({ path: '/home' })
</script>
</body>
(adsbygoogle = window.adsbygoogle || []).push({});