接上篇,我们继续讲解vue router
的核心内容。
1、编程式导航
导航,简单来说,就是切换页面。
在上一篇文章中,我们使用RouterLink
组件,实现了导航功能。
本小节,我们使用编程式导航
的方法,实现导航。
在实际业务中,可能会存在这样的场景。例如,点击一个button
组件,跳转到某个页面。
这时,我们就需要给这个button
提供一个函数实现这个功能。
如何实现呢?
很简单,就是在函数里,使用router.push
语法,将一个json结构体填写进去。
对象结构体里的参数如下:
{
`path`:导航路径。
`query`:请求参数。
`name`:请求路径的命名。
`params`:路径中冒号参数具体参数值。
}
首先,我们将routes
路由配置进行调整。(注:这里暂时还没有用到上面提的push语法
)
我们在routes
配置中,增加了name=about,name=child
。
这些参数,后面会用到。它可以简化路由导航的请求参数配置,避免编写繁琐的、完整的path
路径。
代码如下:
//router.js
import {
createMemoryHistory, createRouter, createWebHashHistory } from 'vue-router'
import HomeView from './HomeView.vue'
import AboutView from './AboutView.vue'
import ChildView from './ChildView.vue'
const routes = [
{
path: '/', component: HomeView },
{
path: '/about/:user/:id',
component: AboutView,
name: 'about',
children: [
{
path: 'child/:id1',
component: ChildView,
name: 'child'
}
]
},
]
const router = createRouter({
history: createMemoryHistory(),
routes,
})
export default router
接着,调整AppRouter.vue
,使用push
函数。
代码如下:
<template>
<h1>这是首页</h1>
<button class="bt" @click="aboutDaohang">
这有一个about导航button
</button>
<br>
<button class="bt" @click="childDaohang">
这有一个child导航button
</button>
<p>
<strong>访问的路径:</strong> {
{ $route.fullPath }}
</p>
<nav>
<li>
<RouterLink to="/">回到主页</RouterLink>
</li>
<li>
<RouterLink to="/about/jim/1