vue-router的简单使用

  1. 安装

    cnpm install vue-router -S

    或 yarn add vue-router -S

  2. 引入,如果是在脚手架中,引入VueRouter之后,需要通过Vue.use来注册插件

    router/index.js文件

    import Vue from 'vue'
    import Router from 'vue-router'
    Vue.use(Router)
    
  3. 创建router路由器

    new Router({
    	routers:[
    		{path:'/main',component:Main}
    	]
    })
    
  4. 创建路由表并配置在路由器中

    //引入组件
    import Home from '@/views/Home'  
    import Center from '@/views/Center'
    
    const routes = [
    	{
    		path:'/home', //path为路径
    		component:Home, //为路径对应的路由组件
    	},
    	{	
            path:'/center',
            component:Center
    	}
    ]
    
    const router = new VueRouter({
      routes
    })
    
    export default router
    
    
  5. 在根实例中注入router,目的是为了让所有的组件里都能通过this. r o u t e r / t h i s . router / this. router/this.route来使用路由的相关功能api

    import router from "./router"
        new Vue({
          el: '#app',
          router,  //注册一下  让组件可以通过this.$router or this.$route 使用路由相关的api属性或方法
          template: '<App/>',
          components: { App }
        })
    
  6. 利用router-view来指定路由切换的位置

    App.vue文件
    <!-- 路由容器 基于slot进行封装的 根据url路径显示不同的路由组件 -->
    <router-view></router-view>
    
  7. 路由切换

    1. 声明式导航 router-link

      //默认会渲染成a标签,可通过tag属性改变渲染的标签
      //to属性用来设置要更改的path信息,并且会根据当前路由的变化为a标签添加对应的router-link-active/router-link-exact-active类名,也可自己添加类名 active-class="active"
      <router-link to="/main" tag="li" active-class="active">main</router-link>
      
      .active{
      	color:red
      }
      
    2. 编程式导航

      //有时候需要在跳转前进行一些动作,router-link直接跳转,需要在方法里使用$router的方法
      this.$router.push('/home')
      
  8. 多级路由

    在创建路由表的时候,可以为每一个路由对象创建children

    属性,值为数组

    {
        path:'/films',  //path为路径
        component:Films,  //为路径对应的路由组件
        // 进行二级路由的配置
        children:[
          {
            path:'/films/nowplaying',   
            component:Nowplaying
          },
          {
            path:'/films/commingsoon',
            component:Commingsoon
          }
        ]
      }
    

    二级路由组件的切换位置依然由router-view来指定(指定在父级路由组件的模板中)

    <router-link to='/films/nowplaying'>nowplaying</router-link>
    <router-link to='/films/commingsoon'>commingsoon</router-link>
    
    <router-view></router-view>
    
  9. 默认路由和重定向

    当我们进入应用,默认想显示某一个路由组件,或者进入某一级路由组件时默认显示其某一个子路由组件,我们可以配置默认路由

    {path:'',component:Home}
    

    当我们需要进入之后重定向到其他路由时,或者url与路由表不匹配时

    {path:'/',redirect:'/main'}
    ///...放在最下面
    {path:'*',redirect:'/main'}
    
  10. 动态路由匹配和命名路由

    命名路由

    可以给路由对象配置name属性,这样的话,在跳转的时候直接写 name:detail就会快速的找到此name属性对应的路由

    路由传参

    有时我们需要在路由跳转的时候传递参数,路由传参的形式主要有两种: 路由传参 、queryString参数

    路由参数需要在路由表里设置

    {path:'/user/:id',component:User} //给User路由配置接收id的参数,多个参数继续在后面设置
    

    在组件中可以通过this.$route.params来使用

    console.log(this.$route.params.id)
    

    queryString参数不需要在路由表设置接收,直接设置?后面的内容,在路由组件中通过this.$route.query接收

    <div class="nowplaying">
            正在热映....
            <!-- <ul>
                <li 
                    v-for="data in datalist"
                    :key="data"
                    @click="toDetail(data)"
                >{{data}}</li>
            </ul> -->
    
            <!-- <ul>
                <router-link
                    v-for="data in datalist"
                    :key="data"
                    :to="'/detail/'+data+'?title=文章一'"
                    tag="li"
                >{{data}}</router-link>
            </ul> -->
    
            <ul>
                <router-link
                    v-for="data in datalist"
                    :key="data"
                    :to="{
                        name:'detail',
                        params:{id:data},
                        query:{title:'文章二'}                     
                    }"
                    tag="li"
                >{{data}}</router-link>
            </ul>
        </div>
        
        
        <script>
          data(){
                return {
                    datalist:["1111","2222","3333"]
                } 
            }
        </script>
    

    router.js

    {
        name:"detail",
        path:"/detail/:id",
        component:Detail
      }
    
  11. 路由的懒加载

    懒加载也叫延迟加载,即在需要的时候进行加载,随用随载

    {
      path: '/about',
      name: 'about',
      component: () => import('@/views/About')  //采用了路由懒加载方式
     }
    
  12. 路由模式

    路由有两种模式: hash 、history默认会使用hash模式(带#的),如果不想在url里出现hash值,在new VueRouter的时候配置mode值为history来改变路由模式

    const router = new VueRouter({
      mode:'history',
      routes
    })
    

    路由原理:

    hash路由 ====> window.onhashchange监听路径的切换

    history路由 ===> window.onpopstate监听路径的切换

  13. 路由守卫

    在某些情况下,当路由跳转前或跳转后、进入、离开某一个路由前、后,需要做某些操作,就可以使用路由钩子来监听路由的变化

    全局路由钩子

    //进入到某个路由组件之前
    router.beforeEach((to, from, next) => {
    	//会在任意路由跳转前执行,next一定要记着执行,不然路由不能跳转了
      console.log('beforeEach')
      console.log(to,from)
      next()
    })
    
    //进入到某个路由组件之后
    router.afterEach((to, from) => {
        //会在任意路由跳转后执行
      console.log('afterEach')
    })
    

    单个路由钩子

    只有beforeEnter,在进入前执行,to参数就是当前路由

    routes: [
        {
          path: '/film',
          component: Film,
          //当进入到film路由之前,就会触发
          beforeEnter: (to, from, next) => {
            // ...
            next() //必须要执行next之后,对应的Film组件才可以正常显示出来
          }
        }
      ]
    

    路由组件钩子

    //进入到某个组件之前的拦截,获取不到组件内部的this
      beforeRouteEnter (to, from, next) {
        // 在渲染该组件的对应路由被 confirm 前调用
        // 不!能!获取组件实例 `this`
        // 因为当守卫执行前,组件实例还没被创建
    	next()
      },
      
      beforeRouteUpdate (to, from, next) {
        // 在当前路由改变,但是该组件被复用时调用     
        // 举例来说,对于一个带有动态参数的路径 /foo/:id,在 /foo/1 和 /foo/2 之间跳转的时候,
        // 由于会渲染同样的 Foo 组件,因此组件实例会被复用。而这个钩子就会在这个情况下被调用。
        // 可以访问组件实例 `this`
      },
      
      //离开某个组件之前的拦截,获取到组件内部的this
      beforeRouteLeave (to, from, next) {
        // 导航离开该组件的对应路由时调用
        // 可以访问组件实例 `this`
    	next()
      }
    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值