路由的使用
路由的使用就是根据匹配的路径信息将正确的组件渲染到模板中定义的的位置。其中使用路由有两种方式:第一种是, 另外一种就是编程式路由。
路由使用的方式
1. router-link声明式路由
这种方式主要是通过router-link组件,配置to属性就可以实现路由的切换,router-link默认会渲染成a标签。
// 模板中使用router-link
<p>
<router-link to="/home">home</router-link>
<router-link to="/about">about</router-link>
</p >
<router-view></router-view>
// 配置的路由信息
routes: [
{
path: '/',
name: 'HelloWorld',
component: HelloWorld
},
{
path: '/home',
name: 'home',
component: Home
},
{
path: '/about',
name: 'about',
component: About
}
]
router-link组件中有很多属性,可以官网查看
2. 编程式路由
编程式路由主要是借助router的实例上的方法来进行编程,点击按钮调用router实例上的方法从而实现路由的跳转。常用到的方法有下面几种。
2.1 router.push
想要导航到不同的 URL,则使用 router.push 方法。这个方法会向 history 栈添加一个新的记录,所以,当用户点击浏览器后退按钮时,则回到之前的 URL。 其实对于上面的router-link来说,配置的to属性,内部也是调用router.push方法。
router.push主要有以下几种使用方式
<p>
<button @click="linkToHome">home</button>
<button @click="linkToAbout">about</button>
</p >
<router-view></router-view>
linkToHome () {
// 字符串
this.$router.push('home')
// 对象
this.$router.push({ path: 'home' })
},
linkToAbout () {
const userId = '123'
// 命名的路由
this.$router.push({ name: 'about', params: {id: '123'} }) // /#/about/123
// 带查询的参数
this.$router.push({ path: 'about', query: {id: '123'} }) // /#/about?id=123
this.$router.push({ name: 'about', params: { userId } }) // /#/about/123
this.$router.push({ path: `/about/${userId}` }) // /#//about/123
this.$router.push({ path: '/about', params: {userId} }) // /#/about
}
上述代码中关于this.$router.push()里面的规则同样适用于router-link中的to属性。
2.2 router.replace
router.replace也可以实现路由的切换,只是它和router.push不同的是push会往history中添加新记录,而replace是会替换掉当前的history记录。
router.replace相当于给router-link组件添加replace属性。
<router-link to="/home" replace>home</router-link>
2.3 router.go
router.go是用来直接操作history记录的,接收一个整数作为参数。表示在history记录中向前或者向后退多少步,类似window.history.go(n)。
<button @click="forward">前进</button>
<button @click="back">后退</button>
forward () {
this.$router.go(1)
// 相当于
// window.history.forward()
},
back () {
this.$router.go(-1)
// 相当于
// window.history.back()
}
传入其他的数字
正数表示前进多少步,如果history记录不够用,那就会失败。负数表示后退多少步,如果history记录不够用,也会失败。
// 前进三步
this.$router.go(3)
// 后退三步
this.$router.go(-3)