路由管理器——Vue Router

228 阅读1分钟

小知识,大挑战!本文正在参与“程序员必备小知识”创作活动。

摘要

Vue Router 是 Vue.js 官方的路由管理器,和 Vue.js 核心深度集成,构建单页面变得易如反掌。

安装

CDN/直接下载

<script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script>
<script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>

NPM

npm install vue-router

正文

声明式导航:使用 <router-link> 创建 a 标签定义导航链接

1、基本路由写法

const User = { template: '<div>user</div>' }

const router = new VueRouter({
    routes: [{ path: '/user/:id', component: User }]
})

2、嵌套路由

const router = new VueRouter({
    routes: [
        {
            path: '/user/:id',
            component: User,
            children: [
                { path: 'posts', component: UserPosts },
                { path: 'profile', component: UserProfile },
            ]
        },
        { ...其他路由 }
    ] 
})

编程式导航:使用 $router

用法:router.push(location, onComplete?, onAbort?)

可以通过 $router 访问路由实例,如:this.$router.push

// 字符串
router.push('home')

// 对象
router.push({ path: 'home' })

// 命名的路由
router.push({ name: 'user', params: { userId: '123' }})

// 带查询参数
router.push({ path: 'register', query: { plan: 'private' }})
用法参数说明
router.pushlocation, onComplete?, onAbort?向 history 栈添加一个新的记录,如:用户点击浏览器后退按钮后
可以返回之前的 URL,等同于 <router-link :to="...">
router.replacelocation, onComplete?, onAbort?替换掉当前的 history 记录,不会向 history 添加新记录
router.gonn 是整数,表示在 history 记录中前进或后退 n 步

路由组件传参

// 使用 $route 会使之与其对应路由形成高度耦合
const User = {
  template: '<div>User {{ $route.params.id }}</div>'
}
const router = new VueRouter({
  routes: [{ path: '/user/:id', component: User }]
})
// 通过 props 解耦

const User = {
  props: ['id'],
  template: '<div>User {{ id }}</div>'
}
const router = new VueRouter({
  routes: [
    { path: '/user/:id', component: User, props: true }
  ]
})

布尔模式

props 设置成 true,route.params 会设置为组件属性

const router = new VueRouter({
  routes: [
    { path: '/user/:id', component: User, props: true }
  ]
})

对象模式

当 props 是静态的时候有用,会被按原样设置为组件属性

const router = new VueRouter({
  routes: [
    {
      path: '/promotion/from-newsletter',
      component: Promotion,
      props: { newsletterPopup: false }
    }
  ]
})

函数模式

可以将参数转换成另一种类型,将静态值与基于路由的值结合等等

const router = new VueRouter({
  routes: [
    {
      path: '/search',
      component: SearchUser,
      props: route => ({ query: route.query.q })
    }
  ]
})

History 模式 和 Hash 模式

HistoryHash
URL中无 #URL中有 #
前进后退不会重新加载页面,但刷新时会请求服务器,
如果服务器没有响应或者资源,会出现404页面
URL 改变不会重新加载页面,不会包括在 HTTP 请求中
const router = new VueRouter({
  mode: 'history',
  routes: [...]
})