(1)经过router-link进行跳转vue
(2)经过编程导航进行路由跳转编程
(1)使用 <router-link>
映射路由 home.vue 中引入了 header.vue 组件,其中含有导航菜单。 当点击导航菜单的时候,会切换 home.vue 中 <router-link>
中的内容,这种只须要跳转页面,不须要添加验证方法的状况,可使用 <router-link>
来实现导航的功能:浏览器
<template>
<header class="header">
<router-link id="logo" to="/home/first">{{logo}}</router-link>
<ul class="nav">
<li v-for="nav in navs">
<router-link :to="nav.method">{{nav.title}}</router-link>
</li>
</ul>
</template>
复制代码
在编译以后,<router-link>
会被渲染为<a>
标签, to
会被渲染为 href
,当 <router-link>
被点击的时候,url 会发生相应的改变,若是使用v-bind 指令,还能够在 to 后面接变量,配合 v-for 指令能够渲染导航菜单。缓存
若是对于全部 id 各不相同的用户,都要使用 home 组件来渲染,能够在 routers.js 中添加动态参数:bash
{
path: '/home/:id',
component: Home
}
复制代码
这样 "/home/user01"、"/home/user02"、"/home/user03" 等路由,都会映射到 Home 组件 而后还可使用 $route.params.id
来获取到对应的 id。session
(2)编程式导航post
实际状况下,有不少按钮在执行跳转以前,还会执行一系列方法,这时能够用 this.$router.push(location)
来修改 url,完成跳转。this
<div>
<button class="register">注册</button>
<button class="sign" @click="goFirst">登陆</button>
</div>
methods: {
goFirst() {
this.$router.push({path: 'home/first'})
}
}
复制代码
push 后面能够是对象,也能够是字符串:url
// 字符串
this.$router.push('/home/first')
复制代码
// 对象
this.$router.push({ path: '/home/first' })
复制代码
// 命名的路由
this.$router.push({ name: 'home', params: { userId: wise }})
复制代码
params: 至关于 post 请求,请求参数不会体如今地址栏中。spa
这种方法会出现以下问题:
若是子页面点击【刷新】按钮时,刚才传过来的参数并不会同步。由于参数没有同步到网页地址栏中。可是若是要让他体如今地址栏中,能够在配置路由时,写在path属性中。 如:
{
path: 'management/target-pv/pv-list/:userId',
component: TARGET_PV_LIST,
name: 'home'
}
浏览器效果以下:
http://localhost:8081/scmis/view/management/target-pv/pv-list/5
复制代码
这样就解决了刷新的问题。
另外还有一种传参形式:query。
query: 至关于 get 请求,请求参数会体如今地址栏中。
this.$router.push({name: 'home', query: {}});
浏览器效果以下:
http://localhost:8081/scmis/view/management/target-pv/pv-list?id=5
复制代码
若是传过来的是一个比较长的参数,咱们既不想让他在url中显示,又想在刷新的时候参数不丢。能够将传过来的参数存起来如本地缓存(localStorage、session等),这样在每次刷新的时候直接从本地缓存中取出。
this.$router
和this.$route
有何区别?上面提到的编程式导航中用this.$router.push()
来改变路由,用this.$route.params.userId
来获得参数值,那么这两个this.$router
和this.$route
看起来很是相近,到底有什么差异呢?
在控制台打印二者能够很明显的看出二者的一些区别,如图:
1.$router
为VueRouter实例,想要导航到不一样URL,则使用$router.push
方法。
2.$route
为当前router跳转对象,里面能够获取name、path、query、params等