vue3中,vue-router的基本使用教程

369 阅读1分钟

安装vue-router

一.直接在脚手架导入

image.png

二.使用npm导入
1.npm i vue-router<br> 2.创建src/router/index.js,以及你要路由的页面
3.在src/router/index.js配置路由项

import { createRouter, createWebHistory } from "vue-router";

export default createRouter({
    history: createWebHistory(),
    routes: [
        {
            path: '/',
            redirect: '/home'
        },
        {
            path: '/home',
            component: () => import('../views/Home.vue')
        },
        {
            path: '/detail',
            component: () => import('../views/Detail.vue')
        },
        {
            path: '/list',
            component: () => import('../views/List.vue')
        }
    ]
})

4.在main.js中use一下

import router from "./router"
app.use(router)

5.配置路由出口 <router-view />

<template>
  <router-view></router-view>
</template>

路由跳转

<template>
    列表页
    <button @click="goDetail(123)">goDetail</button>
    <button @click="goHomeQuery(123)">goHomeQuery</button>

</template>

<script setup>
// 先导入,并创建router对象
import {useRouter} from 'vue-router'
const router = useRouter()

// 1.携带动态路由参数,记得在routes对象的path属性中配置
const goDetail = id => {
    router.push('/detail/' + id)
}

// 2.携带query参数
const goHomeQuery = id => {
    router.push('/home?id=' + id)
}
</script>


// 动态路由传参需要的配置
{
    path: '/detail/:id',
    component: () => import('../views/Detail.vue')
},

补充:

在二次封装axios时,为了在处理401之后海恩那个回到原页面,我们需要获取当前页面的路由路径 router.currentRoute.value.fullPath