前端路由 vue-router

1、路由的基本使用

第一步:创建路由组件的组件;

第二步:配置路由映射:组件和路径映射关系的routes数组;

第三步:通过createRouter创建路由对象,并且传入routes和history模式;

第四步:使用路由:通过<router-link>和<router-view>;

2、路由的默认路径

const routes = [
  { path: '/', redirect: '/home' },
  { path: '/home', component: HomeView },
  { path: '/about', component: AboutView }
]

3、history模式

import { createRouter, createWebHashHistory } from 'vue-router'
​
const router = createRouter({
  routes,
  history: createWebHashHistory()
})

4、router-link

to属性:是一个字符串,或者是一个对象

    <router-link to="/home">Home</router-link> |

replace属性:设置replace属性的话,当点击时,会调用router.replace(),而不是router.push();

active-class属性:设置激活a元素后应用的class,默认是router-link-active

exact-active-class属性:链接精准激活时,应用于渲染的<a>的class,默认是router-link-exact-active;

5、路由懒加载

const AboutView = () => import('../views/AboutView.vue')
​
const routes = [
  { path: '/', redirect: '/home' },
  { path: '/home', component: () => import('../views/HomeView.vue') },
  { path: '/about', component: AboutView }
]

6、路由的其他属性

name属性:路由记录独一无二的名称;

meta属性:自定义的数据

  {
    path: '/about',
    component: AboutView,
    name: 'about',
    meta: { name: 'xueyg', age: 18 }
  }

7、动态路由基本匹配

在Vue Router中,我们可以在路径中使用一个动态字段来实现,我们称之为路径参数

  { path: '/user/:id', component: () => import('../views/UserView.vue') },

在router-link中进行如下跳转:

    <router-link to="/user/123">User</router-link>

8、获取动态路由的值

<script setup>
    import { useRoute } from 'vue-router'
    const router = useRoute()
    console.log(router.params.id)
</script>

9、匹配多个参数

  { path: '/user/:id/info/:name', component: () => import('../views/UserView.vue') },

10、NotFound

  {
    path: '/:pathMatch(.*)',
    component: () => import('../views/NotFound.vue')
  }

我们可以通过$route.params.pathMatch获取到传入的参数:

 <h2>Not Found:{
  
  { $route.params.pathMatch }}</h2>

匹配规则加*和不加的区别

11、路由的嵌套

{
    path: '/about',
    component: AboutView,
    children: [
      {
        path: 'shops',
        component: () => import('../views/AboutShops.vue')
      },
      {
        path: 'goods',
        component: () => import('../views/AboutGoods.vue')
      }
    ]
  },

12、代码的页面跳转

import { useRouter } from 'vue-router'
const router = useRouter()
const PushGoods = () => {
  router.replace('/about/goods')
}
第二种:
 methods: {
    const PushGoods = () => {
      this.$router.push('/about/goods')
    }
 },  

13、query方式的参数

    PushGoods () {
      this.$router.push({
        path: '/about/goods',
        query: {
          name: 'xueyg',
          age: 18
        }
      })
    }

接收参数

    <h2>query:{
   
   { $route.query.name }}</h2>

14、页面的前进后退

      this.$router.go(1) //前进1步
      this.$router.go(-1) // 后退一步
​
      this.$router.forward()
      this.$router.back()

15、router-link的v-slot

v-slot基础使用

1、需要使用custom表示我们整个元素要自定义

2、我们使用v-slot来作用域插槽来获取内部传给我们的值

  <router-link
      to="/home"
      custom
      v-slot="{ href, navigate, route, isActive, isExactActive }"
    >
      <p @click="navigate">跳转about</p> //触发导航的函数
      <div>
        <p>href:{
   
   { href }}</p> //解析后的url
        <p>route:{
   
   { route }}</p> //解析后的规范化的route对象
        <p>isactive:{
   
   { isActive }}</p> //是否匹配的状态
        <p>isExactActive:{
   
   { isExactActive }}</p> //是否是精准匹配的状态
      </div>
    </router-link>

16、router-view的v-slot

router-view也提供给我们一个插槽,可以用于<transition>和<keep-alive>组件来包裹你的路由组件

1、Component:要渲染的组件;

2、route:解析出的标准化路由对象;

17、动态添加路由

动态添加一级路由:

const loginRoute = {
  path: '/login',
  component: () => import('../views/LoginView.vue')
}
router.addRoute(loginRoute)

动态添加二级路由

const createSecond = {
  path: 'second',
  component: () => import('../views/SecondRoute.vue')
}
router.addRoute('home', createSecond)

18、动态删除路由

删除路由有以下三种方式:

方式一:添加一个name相同的路由;

方式二:通过removeRoute方法,传入路由的名称;

方式三:通过addRoute方法的返回值回调;

第一种:
router.addRoute({ path: '/about', name: 'login', component: About })
router.addRoute({ path: '/login', name: 'login', component: Login })
​
第二种:  
router.removeRoute('login')
​
第三种: 
const removeRoute = router.addRoute(loginRoute)
removeRoute()

19、路由导航守卫

全局的前置守卫beforeEach是在导航触发时会被回调的:

1、参数:

to:即将进入的路由Route对象;

from:即将离开的路由Route对象;

2、返回值

a、false:取消当前导航;

b、不返回或者undefined:进行默认导航;

c、返回一个路由地址:1、可以是一个string类型的路径;2、可以是一个对象,对象中包含path、query、 params等信息

d、可选的第三个参数:next(vue3中不再推荐使用)

router.beforeEach((to, from) => {
  if (to.path !== '/login') {
    const token = window.localStorage.getItem('token')
    if (!token) {
      return {
        path: '/login'
      }
    }
  }
})

20、其他导航守卫

完整的导航解析流程:(官网地址:导航守卫 | Vue Router

  1. 导航被触发。

  2. 在失活的组件里调用 beforeRouteLeave 守卫。

  3. 调用全局的 beforeEach 守卫。

  4. 在重用的组件里调用 beforeRouteUpdate 守卫(2.2+)。

  5. 在路由配置里调用 beforeEnter

  6. 解析异步路由组件。

  7. 在被激活的组件里调用 beforeRouteEnter

  8. 调用全局的 beforeResolve 守卫(2.5+)。

  9. 导航被确认。

  10. 调用全局的 afterEach 钩子。

  11. 触发 DOM 更新。

  12. 调用 beforeRouteEnter 守卫中传给 next 的回调函数,创建好的组件实例会作为回调函数的参数传入。

猜你喜欢

转载自blog.csdn.net/znhyXYG/article/details/126471047
今日推荐