# router

Vue Router (opens new window)

# 介绍

Vue Router是Vue.js的官方路由。

# 安装

# npm安装
npm install vue-router@4

# yarn安装
yarn add vue-router@4
<!-- -->
<router-link to="/">首页</router-link>

# router-view

将渲染与路由匹配的组件

<router-view></router-view>
// 1.定义路由组件
const Home = 
// 2.定义路由
const routes = [
  {
    path:'/',	// 路由规则
    component:Home	// 组件
  }
]
// 3.创建路由实例
// 

# 动态路由

:

# 路由匹配语法

# 参数自定义正则

# 可重复参数

# 嵌套路由

const routes = [
  {
    path:'/user/:id',
    component:User,
    children:[
      {
        path:'child',
        component:UserChild
      }
    ]
  }
]

注意:以 / 开头的嵌套路径将被视为根路径。

# 编程式导航

# push

router.push() 方法会向history栈添加一个新的记录,支持点击浏览器后退按钮回到之前的URL地址。

声明式 编程式
<router-link :to=""> router.push()
// 字符串路径
router.push('/home')
// 带路径的对象
router.push({path:'/home'})

// 命名的路由,并加上参数,让路由建立 url
router.push({ name: 'home', params: { username: 'xiaosutongxue' } })

// 带查询参数,结果是 /home?name=xiaosutongxue
router.push({ path: '/home', query: { name: 'xiaosutongxue' } })

// 带 hash,结果是 /home#name
router.push({ path: '/home', hash: '#name' })

注意:如果提供了 pathparams 会被忽略

# replace

router.replace() 方法不会向history添加新纪录,它会替换当前的条目

router.push({ path: '/home', replace: true })
// 相当于
router.replace({ path: '/home' })

# go

该方法采用一个整数作为参数,表示在历史堆栈中前进或后退多少步,类似于 window.history.go(n)

// 向前移动一条记录,与 router.forward() 相同
router.go(1)

// 返回一条记录,与 router.back() 相同
router.go(-1)

// 前进 3 条记录
router.go(3)

// 如果没有那么多记录,静默失败
router.go(-100)
router.go(100)

# 路由守卫