vue(七)路由 vue-router

发布时间 2023-07-06 20:30:52作者: huiyii

安装和使用

通过vue-router路由管理页面之间的关系,是Vue.js的官方路由

1、安装路由 npm install --save vue-router

2、配置路由文件 route/index.js

// 导入路由库
import {createRouter,createWebHashHistory} from "vue-router" 
// 导入静态页面
import Homeview from "../views/Homeview"

// 创建路由定义数组
const routes=[
    {
        path:"/",   // 指定路径
        name:"home",
        component:Homeview  //指定页面的组件
    },
    {
        path:"/about",
        name:"about",
        component: () => import ("../views/Aboutview") //异步加载,未使用就不加载,使用才加载
    }
]
// 创建路由
const router=createRouter({history:createWebHashHistory(),routes})

export default router;

         创建路由有两种方式 createWebHashHistory()createWebHistory()。区别如下:

// 路由后面带#,如 http://localhost:8080/#/about
// 不需要后端处理重定向
// 原理:a标签锚点链接
// 推荐
const router=createRouter({history:createWebHashHistory(),routes})

// 页面显示 http://localhost:8080/about
// 需要后端处理重定向,否则出现404
// 原理:H5的pushState()
// 不推荐
const router=createRouter({history:createWebHistory(),routes})

3、引入路由到项目,在main.js中添加配置

import router from './route'

const app= createApp(App)
app.use(router)

4、指定路由显示入口和路由跳转

<template>
    // 指定路由显示入口
  <RouterView></RouterView>
  // 指定路由跳转,to=route/index.js中定义的path
  <RouterLink to="/">首页</RouterLink>
  <RouterLink to="/about">关于页面</RouterLink>
</template>

路由传递参数

1、在路由配置中指定参数的key

const routes=[
    {
        path:"/about/:pageFrom", // :后设置参数 pageFrom
        name:"about",
        component:Aboutview
    }
]

2、在跳转过程中携带参数

<RouterLink to="/about/从首页来">关于页面</RouterLink>

3、读取参数

<P>{{$route.params.pageFrom}}</P>

嵌套路由配置

1、在路由配置中添加子路由配置

const routes=[
    {
        path:"/about",
        name:"about",
        redirect:"/about/1", //重定向默认页面,写全路径
        component:()=> import("../views/Aboutview.vue"),
        // 添加子路由
        children:[
            {
                path:"1", 
                component:()=>import("../views/aboutsub/about1.vue")
            },
            {
                path:"2",
                component:()=>import("../views/aboutsub/about2.vue")
            }
        ]
    }
]

2、在主页面中添加路由跳转

<template>
    <RouterView></RouterView>
    <RouterLink to="/about/1">关于1</RouterLink>
    <RouterLink to="/about/2">关于2</RouterLink>
</template>