vue-router基本用法

541 阅读3分钟

1.起步

  • 0.导入Vue和VueRouter,调用Vue.use(VueRouter)-->1.定义组件-->2.定义路由-->3.创建router实例-->4.创建和挂载根实例
  // 0. 如果使用模块化机制编程,导入Vue和VueRouter,调用Vue.use(VueRouter)

  // 1.定义组件,一般从其他文件import进来
  // import Layout from '@/layout'
  const Foo = {template:'<div>foo</div>'}
  const Bar = {template:'<div>bar</div>'}

  // 2.定义路由
  const routes = [
    {
      path:'/foo',
      component:Foo
    },
    {
      path:'/bar',
      component:Bar
    }
  ]

  // 3.创建router实例
  const router = new VueRouter({
    routes,
  })

  // 创建挂在根实例,可以在任何组件内通过this.$router访问路由,也可以通过this.$route访问当前路由
  const app = new Vue({
    router
  }).$mount('#app')
  
  
  <style>
      /* 当 <router-link> 对应的路由匹配成功,将自动设置 class 属性值 .router-link-active */
    .router-link-active{
      color:teal
    }
  </style>

2.动态路由匹配

  • 某种模式匹配到的所有路由,全部映射到同个组件
  • 比如,对于所有ID不同的用户,都使用User组件来渲染
  • 我们可以在路由路径中使用“动态路径参数” 达到此效果
  • “路径参数”使用冒号标记,当匹配到一个路由时,参数值会被设置到this.$route.params,可以在每个组件内使用
  • 注意: 当使用路由参数时,从/user/foo导航到/user/bar,原来的组件实例会被复用,意味着,组件的生命周期钩子不会被调用
    const User = {
      template:'<div>User</div>'
    }

    // 创建router实例,并定义路由
    const router = new VueRouter({
      routes = [
        {
          path:'/user/:id',
          component:User
        }
      ]
    })

3.响应路由参数变化

  • 复用组件时,相对路由参数的变化做出响应的话,可以使用watch检测$route对象。
  • 或者使用beforeRouteUpdate导航守卫
    watch:{
      '$route'(to,from){
        // 对路由变化做出响应。。。
      }
    }
    beforeRouteUpdate(to,from,next){
      // 对路由变化做出响应。。。
      // 一定要执行next()
    }

4.通配符路由(另外还有高级匹配模式,后期学习)

  • 当使用通配符路由时,$route.params会自动添加一个名为pathMath参数,它包含URL通过通配符被匹配的部分
    const router = new VueRouter({
      {
        // 匹配所有路径
        path:'*'
      },
      {
        // 会匹配以“/user-”开头的任意路径
        // this.$route.push('/user-admin')
        // this.$route.params.pathMatch------admin
        path:'/user-*'
      }
    })

5.嵌套路由

<div id="app">
    <router-view></router-view>
</div>
 const User = {
    template:`<div>
    <h2>User {{$route.params.id}}</h2>
    <router-view></router-view>
    </div>`
  }

  const Home = {
    template:`<div>Home</div>`
  }

  const Profile = {
    template:`<div>Profile</div>`
  }

  const Posts = {
    template:`<div>Posts</div>`
  }

  const router = new VueRouter({
    routes:[
      {
        path:'/user/:id',
        component:User,
        children:[
          // 当‘/user/zf’匹配成功,子路由path=''时,home组件会被渲染在User的<router-view>中
          {
            path:'',
            component:Home
          },
          // 当‘/user/zf/profile’匹配成功,Profile组件会被渲染在User的<router-view>中
          {
            path:'profile',
            component:Profile
          },
           // 当‘/user/zf/posts’匹配成功,Posts组件会被渲染在User的<router-view>中
          {
            path:'posts',
            component:Posts
          }
        ]
      }
    ]
  })

  const App = new Vue({
    router
  }).$mount("#app")

6.编程式导航

// this.$router.push()
// 参数是字符串,
this.$router.push('home')
// 也可以是对象
this.$router.push({path:'home'})
// 命名的路由
this.$router.push({name:'Home',params:{userId:123}})
// 待查询参数,路由变成/register?plan=private
this.$router.push({path:'home',query:{plan:'private'}})

// 注意:如果使用path, params会被忽略。所以params需要和name搭配使用
// 下面两种写法params不会忽略
const userId = '123'
this.$router.push({name:'user',params:{userId}})  //  -> /user/123
this.$router.push({path:`/user/${userId}`})  // -> /user/123

// 这里的params不生效
this.$router.push({path:'/user',params:{userId}})

7. 命名路由

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

声明式导航
<router-link :to="{name:'user',params:{userId}}"></router-link>
编程式导航
this.$router.push({name:'user',params:{userId}})

8.命名视图

  • 一个页面2个视图,而不是嵌套展示(比如sidebar和main)
  • 这个时候可以用命名视图
  <div id="app">
      <router-view class="viewOne"></router-view>
      <router-view class="viewTwo" name="a"></router-view>
      <router-view class="viewThree" name="b"></router-view>
  </div>
  
  
  const Foo = {
    template:`<div>Foo</div>`
  }
  const Bar = {
    template:`<div>bar</div>`
  }
  const Baz = {
    template:`<div>baz</div>`
  }

  const router = new VueRouter({
    routes:[
      {
        path:'/',
        //注意这里是components
        components:{
          default:Foo,
          a:Bar,
          b:Baz
        }
      }
    ]
  })

9.嵌套命名视图

  const router = new VueRouter({
    routes:[
      {
        path:'/setting',
        component:Setting,
        children:[
          {
            path:'email',
            component:Email
          },
          {
            path:'profile',
            components:{
              default:UserProfile,
              helper:UserProfileView
            }
          }
        ]
      }
    ]
  })

10.重定向&别名

  // 从'/a'重定向到'/b'

  const router = new VueRouter({
    routes:[
      {path:'/a',redirect:'/b',alias:'/b'}
      // 或者
      {path:'/a',redirect:{name:'B'}}
      // 或者
      {
        path:'/a',redirect:to=>{
          return '/b'
          // 或者
          return {name:'B'}
        }
      }
    ]
  })

11. 路由组件传参

const User = {
    props:['id'],
    template:`<div>User{{id}}</div>
    `
  }

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

13.权限管理,路由配置

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

Vue.use(VueRouter);

//引入组件
import home from './modules/home'

//无需权限即可看到的页面
export const constantRoutes = [
  {
    path: '/login',
    //懒加载组件,当路由被访问的时候才加载对应组件
    component: () => import('@/views/login/index'),
    hidden: true
  },
  {
    path: '/404',
    component: () => import('@/views/error-page/404'),
    hidden: true
  },
  {
    path: '/401',
    component: () => import('@/views/error-page/401'),
    hidden: true
  }
]

//有权限猜可以看到的页面
export const asyncRoutes = [
  home,
  customerRouter,
  workSchedule,
  customerService,
  platformSheet,
  { path: '*', redirect: '/404', hidden: true }
]

// 创建路由
const createRouter = () => new Router({
  // 不写的话,默认mode:'hash',mode: 'history',需要后端支持
  scrollBehavior: () => ({ y: 0 }),
  routes: constantRoutes
})

const router = createRouter()
export default router;

// 权限管理-重置路由
export function resetRouter(){
    const newRouter = createRouter();
    router.matcher = newRouter.matcher
}