首页 > 其他 > 详细

Vue Router

时间:2020-09-24 16:10:03      阅读:29      评论:0      收藏:0      [点我收藏+]

Vue Router

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

用 Vue.js + Vue Router 创建单页应用,是非常简单的。使用 Vue.js ,我们已经可以通过组合组件来组成应用程序,当你要把 Vue Router 添加进来,我们需要做的是,将组件 (components) 映射到路由 (routes),然后告诉 Vue Router 在哪里渲染它们。

npm install vue-router
import Vue from ‘vue‘
import VueRouter from ‘vue-router‘
import Home from ‘../views/Home.vue‘

Vue.use(VueRouter)

const routes = [
  {
    path: ‘/‘,
    name: ‘Home‘,
    component: Home
  },
  {
    path: ‘/about‘,
    name: ‘About‘,
    component: () => import(‘../views/About.vue‘)
  }
]

const router = new VueRouter({
  routes
})

export default router
<template>
  <div id="app">
    <div id="nav">
      <router-link to="/"> Home </router-link> |
      <router-link to="/about"> About </router-link>
    </div>
    <router-view />
  </div>
</template>

动态路由 : 冒号

const router = new VueRouter({
  routes: [
    // 动态路径参数 以冒号开头
    { path: ‘/user/:id‘, component: User }
  ]
})

参数值会被设置到 this.$route.params

模式 匹配路径 $route.params
/user/:username /user/evan { username: ‘evan‘ }
/user/:username/post/:post_id /user/evan/post/123 { username: ‘evan‘, post_id: ‘123‘ }

嵌套路由 :children

/user/foo/profile                     /user/foo/posts
+------------------+                  +-----------------+
| User             |                  | User            |
| +--------------+ |                  | +-------------+ |
| | Profile      | |  +------------>  | | Posts       | |
| |              | |                  | |             | |
| +--------------+ |                  | +-------------+ |
+------------------+                  +-----------------+
const router = new VueRouter({
  routes: [
    { path: ‘/user/:id‘, component: User,
      children: [
        {
          // 当 /user/:id/profile 匹配成功,
          // UserProfile 会被渲染在 User 的 <router-view> 中
          path: ‘profile‘,
          component: UserProfile
        },
        {
          // 当 /user/:id/posts 匹配成功
          // UserPosts 会被渲染在 User 的 <router-view> 中
          path: ‘posts‘,
          component: UserPosts
        }
      ]
    }
  ]
})

编程式的导航 :this.$router.push/replace/go

除了使用 <router-link> 创建 a 标签来定义导航链接,我们还可以借助 router 的实例方法,通过编写代码来实现。

router.push(location, onComplete?, onAbort?)

这个方法会向 history 栈添加一个新的记录,所以,当用户点击浏览器后退按钮时,则回到之前的 URL。

编程式 声明式
router.push(...) <router-link :to="...">
// 字符串
router.push(‘home‘)

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

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

// 带查询参数,变成 /register?plan=private
router.push({ path: ‘register‘, query: { plan: ‘private‘ }})

router.replace(location, onComplete?, onAbort?)

它不会向 history 添加新记录,而是替换掉当前的 history 记录。

编程式 声明式
router.replace(...) <router-link :to="..." replace>

router.go(n)

这个方法的参数是一个整数,意思是在 history 记录中向前或者后退多少步。

// 在浏览器记录中前进一步,等同于 history.forward()
router.go(1)

// 后退一步记录,等同于 history.back()
router.go(-1)

命名路由 :name

const router = new VueRouter({
  routes: [
    {
      path: ‘/user/:userId‘,
      name: ‘user‘,  //设置路由名称name: ‘user‘,命名路由
      component: User
    }
  ]
})
<!-- 根据name: ‘user‘跳转页面 -->
<router-link :to="{ name: ‘user‘, params: { userId: 123 }}">User</router-link> 
router.push({ name: ‘user‘, params: { userId: 123 }})

这两种方式都会把路由导航到 /user/123 路径。

命名视图 :components

有时候想同时 (同级) 展示多个视图,而不是嵌套展示,例如创建一个布局,有 sidebar (侧导航) 和 main (主内容) 两个视图,这个时候命名视图就派上用场了。你可以在界面中拥有多个单独命名的视图,而不是只有一个单独的出口。如果 router-view 没有设置名字,那么默认为 default

<router-view class="view one"></router-view>
<router-view class="view two" name="a"></router-view>
<router-view class="view three" name="b"></router-view>

一个视图使用一个组件渲染,因此对于同个路由,多个视图就需要多个组件。

const router = new VueRouter({
  routes: [
    {
      path: ‘/‘,
      components: {
        default: Foo,
        a: Bar,
        b: Baz
      }
    }
  ]
})

重定向 :redirect

是从 /a 重定向到 /b

const router = new VueRouter({
  routes: [
    { path: ‘/a‘, redirect: ‘/b‘ }
  ]
})

重定向的目标也可以是一个命名的路由:

const router = new VueRouter({
  routes: [
    { path: ‘/a‘, redirect: { name: ‘foo‘ }}
  ]
})

甚至是一个方法,动态返回重定向目标:

const router = new VueRouter({
  routes: [
    { path: ‘/a‘, redirect: to => {
      // 方法接收 目标路由 作为参数
      // return 重定向的 字符串路径/路径对象
    }}
  ]
})

别名 :alias

/a 的别名是 /b,意味着,当用户访问 /b 时,URL 会保持为 /b,但是路由匹配则为 /a,就像用户访问 /a 一样。

const router = new VueRouter({
  routes: [
    { path: ‘/a‘, component: A, alias: ‘/b‘ }
  ]
})

路由组件传参 : props

在组件中使用 $route 会使之与其对应路由形成高度耦合,从而使组件只能在某些特定的 URL 上使用,限制了其灵活性。使用 props 将组件和路由解耦:

如果 props 被设置为 trueroute.params 将会被设置为组件属性。

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

    // 对于包含命名视图的路由,你必须分别为每个命名视图添加 `props` 选项:
    {
      path: ‘/user/:id‘,
      components: { default: User, sidebar: Sidebar },
      props: { default: true, sidebar: false }
    }
  ]
})

如果 props 是一个对象,它会被按原样设置为组件属性。

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

导航守卫

路由跳转时,在跳转前或者跳转后,触发的一些方法。

全局前置守卫:beforeEach

所有界面跳转前,都会触发的方法。

const router = new VueRouter({ ... })

router.beforeEach((to, from, next) => {
  // ...
})

每个守卫方法接收三个参数:

  • to:界面要跳转到哪的路由对象
  • from: 界面从哪跳转的路由对象
  • next():跳转
  • next(false):不跳转
  • next(‘/‘)或者 next({ path: ‘/‘ }): 跳转到一个不同的地址。

全局后置钩子:afterEach

所有界面跳转之后,都会触发的方法。

router.afterEach((to, from) => {
  // ...
})

路由独享的守卫:beforeEnter

你可以在路由配置上直接定义 beforeEnter 守卫:

const router = new VueRouter({
  routes: [
    {
      path: ‘/foo‘,
      component: Foo,
      beforeEnter: (to, from, next) => {
        // ...
      }
    }
  ]
})

这些守卫与全局前置守卫的方法参数是一样的。

组件内的守卫:beforeRouteEnter/Update/Leave

最后,你可以在路由组件内直接定义路由导航守卫

const Foo = {
  template: `...`,
  beforeRouteEnter (to, from, next) {
    // 在渲染该组件的对应路由被 confirm 前调用
    // 不!能!获取组件实例 `this`
    // 因为当守卫执行前,组件实例还没被创建
  },
  beforeRouteUpdate (to, from, next) {
    // 在当前路由改变,但是该组件被复用时调用
    // 举例来说,对于一个带有动态参数的路径 /foo/:id,在 /foo/1 和 /foo/2 之间跳转的时候,
    // 由于会渲染同样的 Foo 组件,因此组件实例会被复用。而这个钩子就会在这个情况下被调用。
    // 可以访问组件实例 `this`
  },
  beforeRouteLeave (to, from, next) {
    // 导航离开该组件的对应路由时调用
    // 可以访问组件实例 `this`
  }
}

路由元信息:meta

定义路由的时候可以配置 meta 字段,用来描述这个路由的信息:

const router = new VueRouter({
  routes: [
    {
      path: ‘/foo‘,
      component: Foo,
      children: [
        {
          path: ‘bar‘,
          component: Bar,
          // a meta field
          meta: { requiresAuth: true }
        }
      ]
    }
  ]
})

通过route.meta.requiresAuth可以访问到路由元信息。

过渡动效:transition

可以在<router-view>上添加<transition>标签,结合animate css,这样路由跳转就会有动画。

<transition>
  <router-view></router-view>
</transition>

Vue Router

原文:https://www.cnblogs.com/yinrz/p/13722944.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!