Vue-Router笔记

一.安装路由

npm install vue-router --save

二.配置路由

  • 在src下面创建一个router目录

  • 在router目录下面创建一个index.js

  • 在index.js文件中添加如下结构的内容

    import VueRouter from 'vue-router'
    import Vue from 'vue'
    
    //1. 通过Vue.use(插件),安装插件
    Vue.use(VueRouter)
    // 组件与路由之间的映射关系
    const routes = [];
    // 2.创建路由对象
    const router = new VueRouter({
        // 配置路由与组件之间的映射关系.
        routes
    })
    // 3. 将router对象传入到vue实例
    export default router
    
  • 在main.js文件中将创建的路由实例挂载到Vue实例上.

    import router from "./router";
    new Vue({
        render: h => h(App),
        // 4. vue实例上面挂载路由对象.
        router,
    }).$mount('#app')
    
    

三.配置路由与组件的映射关系

  • 创建组件,我这儿创建两个组件,Home.Vue 和 About.Vue

    <template>
        <div>
            <h2>我是主页</h2>
        </div>
    </template>
    
    <script>
        export default {
            name: "Home"
        }
    </script>
    
    <style scoped>
    
    </style>
    
    <template>
        <div>
           <h2> 我是About</h2>
        </div>
    </template>
    
    <script>
        export default {
            name: "About"
        }
    </script>
    
    <style scoped>
    
    </style>
    
  • 在router/index.js中配置路由与组件的映射关系

    import Home from '../components/Home'
    import About from "../components/About";
    
    const routes = [
        {
            path: '/home',
            component: Home
        },
        {
            path: '/about',
            component: About
        }
    ];
    
  • 在App.Vue中使用路由,这儿需要用到两个标签. router-link 和 router-view

    <template>
        <div id="app">
            <router-link to="/home">首页</router-link>
            <router-link to="/about">关于</router-link>
            <router-view></router-view>
        </div>
    </template>
    

    router-link : 路由对象. 实质就是一个a标签, to属性指向组件的路径

    router-view: 路由组件在App.Vue中的显示位置. 占位.

四. 细节配置

  • 默认路径重定向

    const routes = [
        {
            path: '',
            // 重定向.
            redirect: '/home'
        },
        {
            path: '/home',
            component: Home
        },
        {
            path: '/about',
            component: About
        }
    ];
    

    以上示例,假如浏览器请求 http://127.0.0.1:8080 就会重定向到 http://127.0.0.1:8080/home

  • History模式

    html5默认是hash模式: http://127.0.0.1:8080/#/home, 其中有个#太难看,推荐使用history模式.

    const router = new VueRouter({
        // 配置路由与组件之间的映射关系.
        routes,
        mode:'history'
    })
    

    使用history模式之后,URL显示就是这样: http://127.0.0.1:8080/home

  • router-link

    • to : 路由组件映射的路径

    • tag: router-link渲染成什么样的组件. 比如: tag = 'button', 那么渲染之后就是一个按钮; tag='li', router-link渲染之后就是一个li标签. 默认是a标签.

    • replace : router-link默认是putState模式,使用replace之后,就改成了replace模式.

      <router-link to="/home" replace>首页</router-link>
      
    • active-class: 选中的router-link默认就会有一个router-link-active的class样式. 可以使用active-class对router-link-active进行重命名.

      <router-link to="/about" active-class="active">关于</router-link>
      

      还可以在router/index.js文件中进行统一配置

      const router = new VueRouter({
          // 配置路由与组件之间的映射关系.
          routes,
          mode:'history',
          linkActiveClass:'active'
      })
      
  • $router

    如果想使用代码的方式进行路由跳转.可以使用vue-router提供的$router对象来实现.

            methods:{
                homeClick() {
                    // 触发homeClick方法,跳转到/home
                    this.$router.push('/home')
                },
                aboutClick() {
                    // 触发aboutClick方法,跳转到/about
                    this.$router.push('/about')
                }
            }
    

    除了使用push方法之外,还可以使用replace方法. 使用replace方法之后路由不能前进后退. replace方法与router-link标签中的replace属性作用一样.

五.动态路由

  • 在router/index.js配置动态路由

        {
            // username是动态改变的
            path: '/user/:username',
            component: User
        }
    
  • router-link 标签运态属性绑定

    <router-link :to="'/user/'+username">用户</router-link>
    
  • 从$route对象中获取动态路由参数

       <h2>我是用户....{{$route.params.username}}</h2>
    

    或者通过计算属性

    computed:{
                getUserName() {
                    return this.$route.params.username
                }
            }
    
      <h2>我是用户....{{getUserName}}</h2>
    

六.路由的懒加载

  • 路由懒加载即是路由到那个模块,就加载那个模块组件的代码.
import VueRouter from 'vue-router'
import Vue from 'vue'
import Home from '../components/Home'
import About from '../components/About'
import User from '../components/User'

//1. 通过Vue.use(插件),安装插件
Vue.use(VueRouter)
// 2.创建路由对象
const routes = [
    {
        path: '',
        // 重定向.
        redirect: '/home'
    },
    {
        path: '/home',
        component: Home
    },
    {
        path: '/about',
        component: About
    }
    ,
    {
        // username是动态改变的
        path: '/user/:username',
        component: User
    }
];
const router = new VueRouter({
    // 配置路由与组件之间的映射关系.
    routes,
    mode: 'history',
    linkActiveClass: 'active'
})
// 3. 将router对象传入到vue实例
export default router

以上代码的路由配置不是懒加载模式.所有的js代码会打包成一个js文件. 浏览器请求时,会一次性的将打包js文件从请服务器请求到浏览器端.

  • 懒加载配置
import VueRouter from 'vue-router'
import Vue from 'vue'
// import Home from '../components/Home'
// import About from '../components/About'
// import User from '../components/User'

//1. 通过Vue.use(插件),安装插件
Vue.use(VueRouter)
// 2.创建路由对象
const routes = [
    {
        path: '',
        // 重定向.
        redirect: '/home'
    },
    {
        path: '/home',
        component: () => import('../components/Home')
    },
    {
        path: '/about',
        component: ()=> import('../components/About')
    }
    ,
    {
        // username是动态改变的
        path: '/user/:username',
        component: ()=> import('../components/User')
    }
];
const router = new VueRouter({
    // 配置路由与组件之间的映射关系.
    routes,
    mode: 'history',
    linkActiveClass: 'active'
})
// 3. 将router对象传入到vue实例
export default router

七.路由嵌套

  • 实现步骤

    • 创建对应的子组件, 并且在路由映射中配置对应的子路由
    • 在组件内部使用router-view标签 .
  • 代码实现

    • HomeMessage.Vue组件

      <template>
          <div>
              <ul>
                  <li>消息1</li>
                  <li>消息2</li>
                  <li>消息3</li>
                  <li>消息4</li>
              </ul>
          </div>
      </template>
      
      <script>
          export default {
              name: "HomeMessage"
          }
      </script>
      
      <style scoped>
      
      </style>
      
    • HomeNews.Vue组件

      <template>
          <div>
              <ul>
                  <li>新闻1</li>
                  <li>新闻2</li>
                  <li>新闻3</li>
                  <li>新闻4</li>
              </ul>
          </div>
      </template>
      
      <script>
          export default {
              name: "HomeNews"
          }
      </script>
      
      <style scoped>
      
      </style>
      
    • router/index.js文件中配置子路由

      import VueRouter from 'vue-router'
      import Vue from 'vue'
      //1. 通过Vue.use(插件),安装插件
      Vue.use(VueRouter)
      // 2.创建路由对象
      const routes = [
          {
              path: '',
              // 重定向.
              redirect: '/home'
          },
          {
              path: '/home',
              component: () => import('../components/Home'),
              children: [
                  {
                      path: '/home/news',
                      component: () => import('../components/HomeNews')
                  },
                  {
                      // path: '/home/message',  // 可以这样,绝对路径
                      path: 'message',  // 可以这样,相对路径
                      component: () => import('../components/HomeMessage')
                  }
              ]
          },
          {
              path: '/about',
              component: () => import('../components/About')
          }
          ,
          {
              // username是动态改变的
              path: '/user/:username',
              component: () => import('../components/User')
          }
      ];
      const router = new VueRouter({
          // 配置路由与组件之间的映射关系.
          routes,
          mode: 'history',
          linkActiveClass: 'active'
      })
      // 3. 将router对象传入到vue实例
      export default router
      

      或者

      import VueRouter from 'vue-router'
      import Vue from 'vue'
      
      const Home = () => import('../components/Home')
      const HomeNews = () => import('../components/HomeNews')
      const HomeMessage = () => import('../components/HomeMessage')
      //1. 通过Vue.use(插件),安装插件
      Vue.use(VueRouter)
      // 2.创建路由对象
      const routes = [
          {
              path: '',
              // 重定向.
              redirect: '/home'
          },
          {
              path: '/home',
              component: Home,
              children: [
                  {
                      path: '/home/news',
                      component: HomeNews
                  },
                  {
                      // path: '/home/message',  // 可以这样,绝对路径
                      path: 'message',  // 可以这样,相对路径
                      component: HomeMessage
                  }
              ]
          },
          {
              path: '/about',
              component: () => import('../components/About')
          }
          ,
          {
              // username是动态改变的
              path: '/user/:username',
              component: () => import('../components/User')
          }
      ];
      const router = new VueRouter({
          // 配置路由与组件之间的映射关系.
          routes,
          mode: 'history',
          linkActiveClass: 'active'
      })
      // 3. 将router对象传入到vue实例
      export default router
      

      使用上面这种方式配置路由映射关系进,router-link标签的to属性不能使用相对路径

      <router-link to="news" >新闻</router-link>   <--路由失败-->
      <router-link to="/home/news" >新闻</router-link>  <--路由成功-->
      
    • 在Home.Vue组件中配置两个子路由

      <template>
          <div>
              <h2>我是主页</h2>
              <router-link to="/home/news" >新闻</router-link>
              <router-link to="/home/message">消息</router-link>
              <router-view></router-view>
          </div>
      </template>
      

八.参数传递

  • 路由动态传参的两种类型, params类型与query类型.

8.1 params类型

  • 配置路由格式: /router/:id

        {
            // username是动态改变的
            path: '/user/:username',
            component: () => import('../components/User')
        }
    
  • 传递的方式: 在path后面跟上对应的值

         <router-link :to="'/user/'+username">用户</router-link>
    
  • 传递后形成的路径: router/123, router/admin等

    http://localhost:8080/user/admin
    
  • 取值方式

    $route.params.username
    

8.2 query类型

  • 配置路由格式: /router . 普通配置

  • 传递的方式: query对象传参

  • 传递的形成的路径 : /router?id=123, 或者/router?name=admin.

  • 取值

    <h2>{{$route.query}}</h2>
    
  • 示例代码

    • 路由映射

         {
              path: '/profile',
              component: Profile
          }
      
    • router-link标签使用

              <router-link :to="{
                  path:'/profile',
                  query:{
                      name: 'admin',
                      age: 18,
                      gender: 'female'
                  }
              }">档案
              </router-link>
      
    • 浏览器显示

      http://localhost:8080/profile?name=admin&age=18&gender=female
      
    • 取值

      <h2>{{$route.query.name}}</h2>
      <h2>{{$route.query.age}}</h2>
      <h2>{{$route.query.gender}}</h2>
      
  • 示例代码2

  • 通过按钮点击跳转路由

      <button @click="profileClick">档案1</button>
    
      methods: {
                profileClick() {
                    this.$router.push({
                        path:'/profile',
                        query:{
                            name:'bide',
                            age:1212,
                            gender:'male'
                        }
                    })
                }
            }
    

8.3 总结

  • 如果传参较多,建议使用query传参.

九.全局导航守卫

​ 在路由发生改变时进行监控(做一些事.)

  • 在router/index.js添加以下配置

    // 路由全局导航穿守卫, 前置钩子. 在路由跳转之前执行.
    router.beforeEach((to,from,next)=>{
        // 从from 跳转到to
        // todo 改tab的title
        document.title = to.matched[0].meta.title
        console.log(to)
        next();
    })
    
  • 在组件路由映射关系中添加meta配置

    const routes = [
        {
            path: '',
            // 重定向.
            redirect: '/home'
        },
        {
            path: '/home',
            component: Home,
    
            children: [
                {
                    path: '/home/news',
                    component: HomeNews
                },
                {
                    // path: '/home/message',  // 可以这样,绝对路径
                    path: 'message',  // 可以这样,相对路径
                    component: HomeMessage
                }
            ],
            meta:{
                title:'首页'
            }
        },
        {
            path: '/about',
            component: () => import('../components/About'),
            meta: {
                title: '关于'
            }
    
        },
        {
            // username是动态改变的
            path: '/user/:username',
            component: () => import('../components/User'),
            meta: {
                title: '用户'
            }
        },
        {
            path: '/profile',
            component: Profile,
            meta: {
                title: '档案'
            }
        }
    ];
    

十. 路由独享守卫

十一.keep-alive

  • 使用keep-alive之后,组件不会每次都是创建 , 可以通过组件的created函数进行验证.

    <keep-alive>
    	<router-view></router-view>
    </keep-alive>
    
  • 两个属性

    • include : 指定那些组件会被缓存,正则表达式或字符串,多个组件用逗号进行分隔

    • exclude : 指定那些组件不会被缓存. 正则表达式或字符串,多个组件用逗号进行分隔

原文地址:https://www.cnblogs.com/z-qinfeng/p/13055042.html