2023,你还不会vue-router吗?

285 阅读1分钟

前言

  vue-router是vue生态中,比较重要的一环。没有他,基本上就没有单页面路由。这个插件也是开源的。vue-router

怎么配置vue-router

  我们想要在任何组件内this.$router访问路由器,也通过this.$route访问当前路由。我们需要通过注入路由器,怎么注入路由器呢?需要在main.js中去配置。

import router from './router';
const app = new Vue({
  router
}).$mount('#app')
//这些代码是写在main.js

在router/index.js中,我们应该怎么去配置呢?

//可以从外部引入其他组件
const routes = [
  { path: '/test1', component: test },
  { path: '/test1', component: test1 }
]

const router = new VueRouter({
  routes 
})
export default router; //需要导出,不然在mian.js中引入不到。

怎么优化vue-router配置

  1. 可以利用路由懒加载,引入组件。Vue路由懒加载实现的方法有两种,第一个是Vue异步组件,第二个是webpack代码分割功能。
const Foo = () =>
  Promise.resolve({
    /* 组件定义对象 */
  })

import('./Foo.vue') // 返回 Promise

router的导航配置

  我们在router/index.js中,需要用router.beforeEach中进行拦截,有tofromnext三个参数,to是去哪里,from是从哪里来,next是放行组件。

怎么配置动态路由

  我们为什么要使用动态路由呢?是因为我们要根据不同的id的来展示不同的页面。而这些页面除了id不同,其他都是相同的。这个时候,我们就可以用动态路由,那么怎么配置动态路由。可以参考下面的代码。

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

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

未完待续。。。后期会更新源码层面的。