那些年我们追过的Vue路由

119 阅读2分钟

一、路由基本使用


import { createRouter, createWebHashHistory } from 'vue-router'
import Films from '../views/Films.vue'
import Cinemas from '../views/Cinemas.vue'
import Center from '../views/Center.vue'
import NotFound from '../views/NotFound.vue'

import Nowplaying from '../views/films/Nowplaying.vue'
import Comingsoon from '../views/films/Comingsoon.vue'

const routes = [
    {
        path: "/films",
        name: "myfilms", //命名路由
        component: Films,
        children: [
            {
                path: "/films/nowplaying",
                component: Nowplaying
            },
            {
                path: "comingsoon",
                component: Comingsoon
            },
            {
                path: "/films",
                redirect: '/films/nowplaying'
            }
        ]
    },
    {
        path: "/cinemas",
        component: Cinemas
    },
    {
        path: "/center",
        alias: "/wode", //别名
        component: Center
    },
    {
        path: "/",
        redirect: "/films"
        // redirect: {
        //     name: "myfilms"
        // }
    },
    {
        path: '/:pathMatch(.*)*',
        component: NotFound
    }
]

const router = createRouter({
    history: createWebHashHistory(), // hash  #/film #/center
    // history /film /center
    routes, // `routes: routes` 的缩写
})

export default router

ps:

1、路由配置中,有name属性的叫命名路由,无name属性的叫无名路由

二、路由重定向与别名

1、重定向两种方法

1、无name属性时

image.png

2、有name属性时

image.png

2、别名

image.png

/center 与 /wode 指向的是同一个页面

image.png

image.png

3、404页面(路径不匹配时显示)

image.png

三、声明式导航

image.png

image.png

四、嵌套路由

关键词:children

image.png

五、编程式导航

this.$router.push(/detail/${id})

六、动态路由匹配

1、第一种方法:路径+路由参数

this.$router.push(/detail/${id})

2、第二种方法:对象写法


 this.$router.push({
      name: "Detail",
      params: {
          myid: id
      }
  })
            

ps:

1、以上两种方式路由配置

image.png

2、地址栏表现形式

image.png

3、详情页参数接收

this.$route.params.myid

3、第三种写法:query 传参


this.$router.push({
      path: '/detail',
      query: {
          myid: id
      }
 })
            

ps:

1、路由配置

image.png

2、地址栏表现形式

image.png

3、详情页参数接收

this.$route.query.myid

七、路由模式

1、hash模式(带#号)

image.png

image.png

2、history模式(好看)

image.png

image.png

八、全局路由拦截

1、前置钩子

1、全局拦截-后台系统,除了登录页面,其他页面都必须授权才能访问。

image.png

2、全局拦截-某几个页面都必须授权才能访问。

image.png

路由配置:

image.png

2、后置钩子

主要用于分析用户行为。

image.png

九、组件内的守卫

1、beforeRouteEnter

image.png

2、beforeRouteUpdate

image.png

3、beforeRouteLeave

image.png

十、路由懒加载

image.png

十一、VCA与路由

1、vca: vue-composition-api

2、vue3中script标签中写入setup,组件直接引入即可使用,不用再单独注册

3、vue3写法


<script setup>
import { useRouter } from 'vue-router'
const router = useRouter()
const handleLogin = () => {
    localStorage.setItem("token", "kerwin")
    router.push("/")
}
</script>

4、beforeRouteEnter不支持vca写法!!!!!!

十二、写在最后

内容比较基础,但比较靠谱和受用,对vue路由又有了更深一层的理解。如果看完本文觉得对你有所帮助,请动动你发财的小手,点个赞赞哈!