路由

  • 路由map
  • 路由视图
  • 路由导航

实现简单路由

import VueRouter from 'vue-router'
Vue.use(VueRouter)

let router = new VueRouter({
  mode: 'history',//这样访问路由就不需要加上/#
  routes: [
    {
      path: '/a',
      component: a
    },
    {
      path: '/b',
      component: b
    }
  ]
})
new Vue({
  router,
  el: '#app',
  render: h => h(App),
  directives: {

  }
})

路由的代码显示在

<router-view></router-view>
<router-link :to="{path:'a'}">to a</router-link>//可以实现转换成a标签跳转
<router-link :to="{path:'b'}">to b</router-link>

实现多层参数路由

let router = new VueRouter({
  mode: 'history',//这样访问路由就不需要加上/#
  routes: [
    {
      path: '/a/:color/detail/:type',
      component: a
    },
    {
      path: '/b',
      component: b
    }
  ]
})

此处
/a/:color/detail/:type
带冒号的表示属性为color,填的任何值都会赋值给color和type

路由嵌套

routes: [
    {
      path: '/a',
      component: a,
      children: [
        {
          path: 'aa',
          component: aa
        }
      ]
    },
    {
      path: '/b',
      component: b,
      children: [
        {
          path: 'bb',
          component: bb
        }
      ]
    }
  ]

子路由渲染在父路由的组件里,所以需要在父路由的组件加上
<router-view></router-view>
同时我们也可以通过
<router-link :to="{path:'b/bb'}">to b bb</router-link>
或者通过代码实现

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

// 对象
this.$router.push({path: '/login?url=' + this.$route.path});

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

// 带查询参数,变成/backend/order?selected=2
this.$router.push({path: '/backend/order', query: {selected: "2"}});

重定向

在routes中加上

{
      path: '/',
      redirect: '/a'
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容