vue-路由的知识总结

目录

一、概念

二、使用步骤

三、路由嵌套 

四、路由命名

五、query参数 和 params参数

5.1、路由的query参数

5.2、路由的params参数 

六、路由的params配置  

6.1、方法一

 6.2、方法二

 6.2、方法三

七、两个新的生命周期钩子(路由)

八、路由守卫

8.1、全局守卫

8.2、独享守卫

8.3、组件内守卫


一、概念

路由用于设定访问路径,并将路径和组件映射起来

一般用Vue做的都是单页应用,只有一个主页面index.html,所以你写的<a></a>标签是不起作用的,要使用vue-router来进行管理。

二、使用步骤

第一步:安装 

npm install vue-router

第二步:在src文件目录下新建一个router文件夹,src/router/index.js,此处就是编写路由组件的地方,这个文件就是路由的核心文件

//该文件专门用于创建整个应用的路由器
import VueRouter from "vue-router"
//引入组件
import About from '../pages/About'
import Home from '../pages/Home'
//创建并暴露一个路由器
const router = new VueRouter({
    routes: [
        {
            path: '/about',
            component:About
        },
        {
            path: '/home',
            component:Home
        }
    ]
})
export default router

第三步:在入口函数里引入相关路由

import Vue from "vue";
import App from './App.vue'
//引入VueRouter
import VueRouter from 'vue-router'
//引入路由器
import router from './router/index'
Vue.config.productionTip = false
//应用插件
Vue.use(VueRouter)

//创建vue
new Vue({
    el: '#app',
    render: h => h(App),
    router:router
})

第四步:新建两个路由组件 ,一般存放在pages文件夹里面

第五部:配置App组件

vue中借助router-link标签实现路由的切换    

<router-link class="list-group-item" active-class="active" to="/about">About</router-link> 

active-class:表示当前活跃的路由高亮显示

<router-view></router-view>:指定组件的内容呈现位置 

<template>
  <div>
    <div class="row"> 
      <div class="col-xs-2 col-xs-offset-2">
        <div class="list-group">
          <!-- 原始html中我们使用a标签实现页面的跳转 -->
          <!-- <a class="list-group-item active" href="./about.html">About</a> -->
          <!-- <a class="list-group-item" href="./home.html">Home</a> -->

          <!-- Vue中借助router-link标签实现路由的切换 -->
          <router-link class="list-group-item" active-class="active" to="/about"
            >About</router-link
          >
          <router-link class="list-group-item" active-class="active" to="/home"
            >Home</router-link
          >
        </div>
      </div>
      <div class="col-xs-6">
        <div class="panel">
          <div class="panel-body">
            <!-- 指定组件的呈现位置 -->
            <router-view></router-view>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>

export default {
  name: "App",
};
</script>

注意点:

  • 路由组件通常存放在pages文件夹里面 ,一般组件通常存放在components文件夹
  • 通过切换,‘隐藏了的路由组件’,默认是被销毁掉的,需要的时候再去挂载
  • 每个组件都有自己的$route属性,里面存储着自己的路由信息
  • 整个应用只有一个router,可以通过组件的$router属性获取到

三、路由嵌套 

跳转要加上父亲路径 即:/home/news

路径:children:[

       {    path:'news'   ,component:News

]

注意path后面不要加 ‘/news’

比如我们要在上面基础步骤里面的home路由组件里面嵌套两个组件 

index.js文件:

const router = new VueRouter({
    routes: [
        {
        
            path: '/about',
            component: About
        },
        {
            path: '/home',
            component: Home,
            children: [
                {
                    path: 'news',
                    component:News,
                },
                {
                    path: 'message',
                    component:Message,
                }
            ]
        }
    ]

那么home组件的展示区就是嵌套组件的呈现位置

home.vue

<template>
  <div>
    <h2>Home组件内容</h2>
    <div>
      <ul class="nav nav-tabs">
        <li>
          <router-link class="list-group-item " active-class="active" to="/home/news">News</router-link>
        </li>
        <li>
          <router-link class="list-group-item " active-class="active" to="/home/message">Message</router-link>
        </li>
      </ul>
      <!-- 指定组件的呈现位置 -->
      <router-view></router-view>
    </div>
  </div>
</template>

<script>
export default {
  name: "Home",
};
</script>

四、路由命名

作用:可以简化路由的跳转

如何使用:

首先给路由命名

const router = new VueRouter({

   routes:[

      {
         name:'guanyu',
         path:'/about',
         component:About
      }
]
})

简化跳转

首先看下没加命名的跳转:

<router-link to ='/demo/test/about'> 跳转 </router-link>

简化后的,直接通过名字跳转

<router-link to='{name:about}'> 跳转 </router-link>

简化写法搭配传递参数

<router-link :to'{name:'about',query:{ id:m.id,title:m.title}}'>{{m.title}}</router-link>

五、query参数 和 params参数

5.1、路由的query参数

传递参数的方法:

方法一:跳转路由并携带query参数,to的字符串写法

<router-link :to="`/home/message/detail? id=${m.id}&title=${m.title}`">{{m.title}}</router-link>

方法二:跳转路由并携带query参数,to的对象写法

<router-link 
   :to="{
        path:'/home/message/detail',
        query:{
            id:m.id,
            title:m.title  
   }">
 {{m.title}}
</router-link>

接受参数的方法:

detail.vue

$route.query.xx

<template>
  <div>
    <ul>
      <li>消息编码:{{$route.query.id}}</li>
      <li>消息编码:{{$route.query.title}}</li>
    </ul>
  </div>
</template>

5.2、路由的params参数 

配置路由:

children: [
         {
              name:'xiangqing',
              path: 'detail/:id/:title', //使用占位符声明接受params参数
              component: Detail,
          }
  ]

传递参数的方法:

方法一:跳转路由并携带params参数,to的字符串写法

<router-link :to="`/home/message/detail/${m.id}/${m.title}`">{{m.title}}</router-link>

方法二:跳转路由并携带params参数,to的对象写法

特别注意:路由携带params参数时,若使用to的对象写法,则不能使用path配置项,必须使用name配

 <router-link
          :to="{
            name: 'xiangqing',
            params: {
              id: m.id,
              title: m.title,
            },
          }"
        >
      {{ m.title }}
</router-link>

接受参数的方法:

detail.vue

$route.params.xx 

<template>
  <div>
    <ul>
      <li>消息编码:{{$route.params.id}}</li>
      <li>消息编码:{{$route.params.title}}</li>
    </ul>
  </div>
</template>

六、路由的params配置  

当父组件携带参数给子路由的时候,子路由可以直接使用,通过params配置后更加简单

作用:让路由组件更加方便的收到参数

之前的:<li>消息编码:{{$route.params.id}}</li>

现在的:  <li>消息编码:{{id}}</li>

6.1、方法一

❤️    路由配置props 【使用少】

children: [
            {
               name: 'xiangqing',
               path: 'detail/:id/:title', //使用占位符声明接受params参数
               component: Detail,
               props: { a: '001', b: '你好' }
             }
 ]
  • 值为对象,该对象中的所有key-value都会以props的形式传给Detail组件

❤️   路由接受props

路由;
<template>
  <div>
    <h2>{{a}}</h2>
    <h2>{{b}}</h2>
  </div>
</template>

export default {
  name: "Detail",
  props:['a','b'],
  mounted() {
    console.log(this.$route);
  },
};

 6.2、方法二

❤️   路由配置props

  • props值为布尔值,为true的时候,就会把该路由组件收到的多有params参数,以props的形式传给detail组件
  •  path: 'detail/:id/:title' :携带的id和title参数都是跳转路径的时候携带的query参数或params参数
 children: [
            {
             name: 'xiangqing',
             path: 'detail/:id/:title', //使用占位符声明接受params参数
             component: Detail,
             props:true
            }
    ]

❤️   路由接受props

<template>
  <div>
    <ul>
      <li>消息编码:{{id}}</li>
      <li>消息编码:{{title}}</li>
    </ul>
  </div>
</template>

 props:['id','title'],	

 6.2、方法三

❤️   路由配置props

children: [
      {
        name: 'xiangqing',
        path: 'detail', //使用占位符声明接受params参数
        component: Detail,

         props($route) {
                 return{
                      id: $route.query.id,
                      title:$route.query.title
                 }
          }
       }
]

❤️   路由接受props

<template>
  <div>
    <ul>
      <li>消息编码:{{id}}</li>
      <li>消息编码:{{title}}</li>
    </ul>
  </div>
</template>
  
props:['id','title'],

七、两个新的生命周期钩子(路由)

作用:路由组件所独有的两个钩子,用于捕获路由组件的激活状态

具体名字:activated 路由组件被激活时触发、deactivted 路由组件失活时触发

即使将news里面的内容缓存起来,在news路由组件失活的时候,定时器也会被关闭,缓存和失活不会相互影响

export default {
  name: "News",
  data() {
    return {
      opacity: 1,
    };
  },
  activated() {
    this.timter = setInterval(() => {
      this.opacity -= 0.01;
      if (this.opacity <= 0) this.opacity = 1;
    }, 16);
  },
  deactivated() {
    clearInterval(this.timter);
  },
};

八、路由守卫

 作用:对路由进行权限控制

分类:全局守卫、独享守卫、组件内守卫

接下来会提到的三个参数:

  1. to 到那个触发的路由
  2. from 从那个路由来的
  3. next  开权限,往下走

注意:如果想要使用后置组件实现离开组件时,上方对应的titile改变,就打开全局守卫里面的后置守卫,因为独享组件守卫和组件内守卫没有后置守卫

8.1、全局守卫

在 router/index.js 文件里配置

meta:{ isAuth:true }.  表示当前这个路由需要被检验

 //路由配置的时候要加上这个配置项:
{
        name: 'xiaoxi',
        path: 'message',
        component: Message,
        meta: {
             isAuth: true, //表示当前这个路由需要被校验
             title:'消息'
         }
     
 }
// 全局前置路由守卫----初始化的时候被调用、每次路由切换之前被嗲用
router.beforeEach((to, from, next) => {
    console.log(to, from);
    if (to.meta.isAuth) { //判断是否需要权限
        if (localStorage.getItem('school') === 'atguigu') {
            next()
        } else {
            alert('学校名不对,无权查看')
        }
    } else {
        next()
    }
})

//全局后置路由守卫---初始化的时候被调用、每次路由切换之后被调用
router.afterEach((to,from) => {
    document.title = to.meta.title || '硅谷系统'
})
export default router

8.2、独享守卫

在 router/index.js里面配置

//二级路由
children: [
        {
          name: 'xinwen',
          path: 'news',
          component: News,
          meta: {
               isAuth: true,
               title:'新闻'
           },
           //独享守卫
           beforeEnter: (to, from, next) => {
              if (to.meta.isAuth) { //判断是否需要权限
                 if (localStorage.getItem('school') === 'atguigu') {
                      next()
                 } else {
                      alert('学校名不对,无权查看')
                 }
              } else {
                   next() 
              }
          }
      },

8.3、组件内守卫

通过路由规则进入该组件时检验 

比如要校验 About 组件

export default {
  name: "About",
  //通过路由规则,进入该组件时被调用
  beforeRouteEnter(to, from, next) {
    if (to.meta.isAuth) {
      //判断是否需要权限
      if (localStorage.getItem("school") === "atguigu") {
        next();
      } else {
        alert("学校名不对,无权查看");
      }
    } else {
      next();
    }
  },

  //通过路由规则,离开该组件时被调用
  beforeRouteLeave (to, from, next) {
    console.log('About--beforeRouterLeave',to,from);
    next()
  }
};
</script>

以上就是总结的vue中路由的基础知识啦 ?    

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
THE END
分享
二维码

)">
< <上一篇
下一篇>>