简介
除了使用 创建 a 标签来定义导航链接,我们还可以通过编程式导航实现导航。所谓编程式导航指的是不通过router-link跳转,而是借助 router 的实例,通过代码的方式跳转。
示例:
App.vue
<template>
<div id="app">
<button @click="toHome">Home</button>
<button @click="toNews">News</button>
<button @click="toDetails">Details</button>
<br>
<router-view></router-view>
</div>
</template>
<script>
export default {
methods: {
toHome () {
this.$router.push('/home')
},
toNews () {
this.$router.push({
path: '/news',
query: { name: 'zhangsan' } //query方式传参
})
},
toDetails () {
this.$router.push({
name: 'Details',
params: { nid: 1001 } //params方式传参
})
}
}
}
</script>
Home.vue
<template>
<div>
<h2>Home</h2>
</div>
</template>
News.vue
<template>
<div>
<h2>News</h2>
{{this.$route.query}} <!—获取query传递过来的数据/ get传值 -->
</div>
</template>
Details.vue
<template>
<div>
<h2>Details</h2>
{{this.$route.params.nid}} <!—获取params传递过来的数据 -->
</div>
</template>
router目录下的index.js
const routes = [{
path: '/home',
component: () => import('../views/Home')
}, {
path: '/news',
component: () => import('../views/News') // 懒加载
}, {
path: '/details/:nid',
name: 'Details',
component: () => import('../views/Details') // 懒加载
}]
效果:
-
默认页面
-
单击Home:
-
单击News:
-
单击Details: