Vue 路由

发布于:2022-11-16 ⋅ 阅读:(495) ⋅ 点赞:(0)

目录

一、基本路由:

二、多级路由 

三、命名路由

四、路由参数

五、路由的 props 配置 

六、的 replace 属性

 七、编程式路由导航

八、缓存路由组件

九、路由守卫


一、基本路由:

        1、安装对应版本的路由: npm i vue-router@...

        2、应用插件:

        Vue.use(VueRouter)

         3、编写router 配置项:

// 该文件专门用于创建整个应用的路由器
import VueRouter from "vue-router";

// 引入组件
import Home from "../components/Home";
import About from "../components/About";

// 创建 并暴露 一个路由器
export default new VueRouter({
    routes: [
        {
            path: "/home",
            component: Home,
        },
        {
            path: "/about",
            component: About,
        },
    ],
});

        4、在切换标题组件中实现切换高亮样式:

<!-- active-class="active" -->
<router-link to="/home" active-class="active" class="list-group-item">Home</router-link>

        5、指定展示位置:

<router-view></router-view>

        6、注意点:

        路由组件通常存放在pages文件夹,一般组件通常存放在components文件夹。

        通过切换,‘隐藏’了的路由组件,默认是被销毁的,需要的时候再去挂载。

        每个组件都有自己的`$route`属性,里面存放着自己的路由信息。

        整个应用只有一个router,可以通过组件的`$router`属性获取到。

二、多级路由 

        1、配置路由规则,使用children配置项:

{
    path: "/home",
    component: Home,
    children: [
        {
            path: "news",
            component: News,
        },
        {
            path: "message",
            component: Message,
        },
    ],
},

        2、跳转(要写完整路径):

<router-link to="/home/news" active-class="active" class="list-group-item">News</router-link>

三、命名路由

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

        2、如何使用:

                (1).给路由命名:

{
    // 命名
    name: "about",
    path: "/about",
    component: About,
},
{
    path: "/home",
    component: Home,
    children: [
        {
            path: "message",
            component: Message,
            children: [
                {
                  name: "xq",
                  path: "detail",
                  component: Detail,
                },
              ],
            },
            {
              path: "news",
              component: News,
            },
          ],
        },

                (2).简化跳转:

<!-- 简化前 -->
<router-link :to="{ path: '/home/message/detail'}">{{ item.title }}</router-link>

<!-- 简化后 -->
<router-link :to="{ name: 'xq'}">{{ item.title }}</router-link>

四、路由参数

        1、query 传参

<!-- 传递参数 -->
<!-- 跳转路由并携带query参数。to的字符串写法 -->
<router-link :to="`/home/message/detail?id=${item.id}&title=${item.title}`" >{{ item.title }}</router-link>

<!-- 跳转路由并携带query参数。to的对象写法 -->
<router-link :to="{ path: '/home/message/detail',query: { id: item.id, title: item.title },}" >{{ item.title }}</router-link >


<!-- 接收参数 -->
<li>消息编号:{{ $route.query.id }}</li>
<li>消息内容:{{ $route.query.title }}</li>

        2、params 传参

<!-- 配置路由,声明接收params参数 -->
     {
        name: "",
        path: "/home",
        component: Home,
        children: [
          {
            name: "",
            path: "message",
            component: Message,
            children: [
              {
                name: "xiangqing",
                // 使用占位符声明接收params参数
                path: "detail/:id/:title",
                component: Detail,
              },
            ],
          },
          {
            name: "",
            path: "news",
            component: News,
          },
        ],
      },

<!-- 传递参数 -->
      <!-- 跳转路由并携带params参数。to的字符串写法 -->
      <router-link
        :to="`/home/message/detail/${item.id}/${item.title}`"
        >{{ item.title }}</router-link
      >

      <!-- 跳转路由并携带params参数。to的对象写法 -->
      <router-link
        :to="{
          name: 'xiangqing',
          params: { id: item.id, title: item.title },
        }"
        >{{ item.title }}</router-link
      >

<!-- 接收参数 -->
$route.params.id
$route.params.title

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

五、路由的 props 配置 

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

    {

      name: "xiangqing",

      // params传参

      // path: "detail/:id/:title",

      // query传参

      path: "detail",

      component: Detail,

      // props的第一种写法 值为对象,

      // 该对象中的所有key-value都会以props的心事传给Detail组件。

      // 该方法的缺点是,数据为死数据

      // props: {

      //   id: "1",

      //   b: "hello",

      // },

      // props的第二种写法 值为布尔值,

      // 若布尔值为真,就会把该路由组件收到的所有params参数,以props的形式传给Detail组件

      // props: true,

      // props的第三种写法 值为函数,

      props($route) {

        return {

          id: $route.query.id,

          title: $route.query.title,

        };

      },

    },

六、<router-link>的 replace 属性

    1、作用:控制路由跳转时操作浏览器历史记录的模式

    2、浏览器的历史记录有两种写入方式:分别为`push`和`replace`,`push`时追加历史记录,`replace`时替换当前记录,路由跳转时候默认为`push`

    3、如何开启`replace`模式:<router-link replace ...></router-link>

 七、编程式路由导航

         1、作用:不借助`<router-link>`实现路由跳转,让路由跳转更加灵活

         2、具体编码:

      //$router  push
      this.$router.push({
        name: "xiangqing",
        params: { id: item.id, title: item.title },
      });

      //replace
      this.$router.replace({
        name: "xiangqing",
        params: { id: item.id, title: item.title },
      });

      //back 前进
      this.$router.back();

      //forward 后退
      this.$router.forward();

      //go  可前可退
      this.$router.go(3);

八、缓存路由组件

         1、作用:让不展示的路由组件保持挂载,不被销毁

         2、具体编码

    <!-- 缓存news这个组件 不写include 意思所有都缓存 -->
    <!-- include 内写的是组件名 -->
    <keep-alive include="userNews">
      <router-view></router-view>
    </keep-alive>

    <!-- 缓存多个 -->
    <keep-alive :include="['userNews','Message']">
      <router-view></router-view>
    </keep-alive>

九、路由守卫

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

        2、全局守卫: 

    {
      name: "gy",
      path: "/about",
      component: About,
      // 路由元信息 isAuth是否授权
      meta: { isAuth: true, title: "关于" },
    },


    //全局前置路由守卫--初始化的时候被调用、每次路由切换之前被调用
    router.beforeEach((to, from, next) => {
      console.log("前置路由守卫", to, from);
      // 判断是否需要权限
      if (to.meta.isAuth) {
        if (localStorage.getItem("school") == "atguigu") {
          // document.title = to.meta.title || "测试系统";
          // 放行
          next();
        } else {
          alert("信息不对,无权查看相关内容");
        }
      } else {
        // document.title = to.meta.title || "测试系统";
        next();
      }
    });

    // 全局后置路由守卫 初始化的时候被调用、每次路由切换之后被调用
    router.afterEach((to, from) => {
      console.log("后置路由守卫", to, from);
      document.title = to.meta.title || "测试系统";
    });

         3、独享守卫

    {
      name: "xinwen",
      path: "news",
      component: News,
      meta: { isAuth: true, title: "新闻" },
      // 独享路由守卫
      beforeEnter: (to, from, next) => {
        if (to.meta.isAuth) {
          if (localStorage.getItem("school") == "atguigu") {
            // document.title = to.meta.title || "测试系统";
            // 放行
            next();
          } else {
            alert("信息不对,无权查看相关内容");
          }
        } else {
          // document.title = to.meta.title || "测试系统";
          next();
        }
      },
    },

        4、组件内路由守卫

    export default {
      name: "uAbout",
      // 通过路由规则,进入该组件时被调用
      beforeRouteEnter(to, from, next) {
        console.log(to, from);
        if (to.meta.isAuth) {
          if (localStorage.getItem("school") == "atguigu") {
            // document.title = to.meta.title || "测试系统";
            // 放行
            next();
          } else {
            alert("信息不对,无权查看相关内容");
          }
        } else {
          // document.title = to.meta.title || "测试系统";
          next();
        }
      },
      // 通过路由规则,离开该组件时被调用
      beforeRouteLeave(to, from, next) {
        console.log(to, from);
        next();
      },
    };

本文含有隐藏内容,请 开通VIP 后查看