Vue router

如果在一个模块化工程中使用它, 必须要通过Vue.use()明确地安装路由功能.

import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

Vue.use(plugin) , 安装Vue.js插件, 该方法需要在调用new Vue()之前被调用,  如果插件是一个对象, 必须提供install方法, 如果插件是个函数, 它会被作为install方法, install方法调用时, 会将Vue作为参数传入, 当install方法被同一个插件多次调用, 插件将只会安装一次.

动态路由匹配

我们经常把某种模式的路由全部映射到同个组件,例如, 我们有一个User组件, 对于所有ID各不相同的用户, 都要使用这个组件来渲染.

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

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

现在, 像/user/foo和/user/bar都将映射到相同的路由.

一个路径参数使用冒号标记, 当匹配到一个路由时, 参数值会被设置到this.$route.params, 可以在每个组件内使用. 于是, 我们可以输出 当前用户的ID:

const User = {
  template: '<div>User {{ $route.params.id }}</div>'
}

嵌套路由

一个被渲染组件同样可以包含自己的嵌套<router-view>,  要在嵌套的出口中渲染组件, 需要在VueRouter的参数中使用children配置:

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
        }
      ]
    }
  ]
})

编程式导航

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

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

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

跟router.push很像, 唯一的不同就是, 它不会向history添加新记录.

(3) router.go(n)

在history记录中向前或者向后退多少步.

命名路由

在创建Router实例的时候, 在routes配置中给某个路由设置名称.

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

命名视图

有时想同时展示多个视图, 例如创建一个布局, 有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
      }
    }
  ]
})

https://router.vuejs.org/zh/guide/

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值