路由


1. 路由

1.1. 对路由的理解

1.2. 基本切换效果

  • Vue3中要使用vue-router的最新版本

  • 路由配置文件index.ts代码如下:

import { createRouter, createWebHistory } from 'vue-router'
import Home from '@/views/Home.vue'
import About from '@/views/About.vue'

const router = createRouter({
    history: createWebHistory(),
    routes: [
        {
            path: '/',
            component: Home
        },
        {
            path: '/about',
            component: About
        }
    ]
})
export default router
  • main.ts代码如下:
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'


const app = createApp(App)

app.use(router)
app.mount('#app')
  • App.vue代码如下
<template>
    <div class="app">
        <h2 class="title">Vue路由测试</h2>
        <!-- 导航区 -->
        <div class="navigate">
            <RouterLink to="/" active-class="active">首页</RouterLink>
            <RouterLink to="/about" active-class="active">关于</RouterLink>
        </div>
        <!-- 展示区 -->
        <div class="main-content">
            <RouterView></RouterView>
        </div>
    </div>
</template>

<script lang="ts" setup name="App">

import { RouterLink, RouterView } from 'vue-router'

</script>

<style scoped>
.title {
    text-align: center;
    word-spacing: 5px;
    margin: 30px 0;
    height: 70px;
    line-height: 70px;
    background-image: linear-gradient(45deg, gray, white);
    border-radius: 10px;
    box-shadow: 0 0 2px;
    font-size: 30px;
}

.navigate {
    display: flex;
    justify-content: space-around;
    margin: 0 100px;
}

.navigate a {
    display: block;
    text-align: center;
    width: 90px;
    height: 40px;
    line-height: 40px;
    border-radius: 10px;
    background-color: gray;
    text-decoration: none;
    color: white;
    font-size: 18px;
    letter-spacing: 5px;
}

.navigate a.active {
    background-color: #64967E;
    color: #ffc268;
    font-weight: 900;
    text-shadow: 0 0 1px black;
    font-family: 微软雅黑;
}

.main-content {
    margin: 0 auto;
    margin-top: 30px;
    border-radius: 10px;
    width: 90%;
    height: 400px;
    border: 1px solid;
}
</style>

1.3. 路由组件存放

  1. 路由组件通常存放在viewspages文件夹,一般组件通常存放在components文件夹

  2. 通过点击导航,视觉效果上“消失” 了的路由组件,默认是被卸载掉的,需要的时候再去挂载

1.4.路由器工作模式

  1. history模式

    优点:URL更加美观,不带有#,更接近传统的网站URL

    缺点:后期项目上线,需要服务端配合处理路径问题,否则刷新会有404错误

    const router = createRouter({
      	history:createWebHistory(), //history模式
      	/******/
    })
  2. hash模式

    优点:兼容性更好,因为不需要服务器端处理路径

    缺点:URL带有#不太美观,且在SEO优化方面相对较差

    const router = createRouter({
      	history:createWebHashHistory(), //hash模式
      	/******/
    })

1.5. to的两种写法

<!-- 第一种:to的字符串写法 -->
<router-link active-class="active" to="/home">主页</router-link>

<!-- 第二种:to的对象写法 -->
<router-link active-class="active" :to="{path:'/home'}">Home</router-link>

1.6. 命名路由

作用:可以简化路由跳转及传参

给路由规则命名:

routes:[
  {
    name:'zhuye',
    path:'/home',
    component:Home
  },
  {
    name:'guanyv',
    path:'/about',
    component:About
  },
]

跳转路由:

<!--简化前:需要写完整的路径(to的字符串写法) -->
<router-link to="/about">跳转</router-link>

<!--简化后:直接通过名字跳转(to的对象写法配合name属性) -->
<router-link :to="{name:'guanyv'}">跳转</router-link>

1.7. 嵌套路由

  1. 编写About的子路由:Detail.vue

  2. 配置路由规则,使用children配置项:

const router = createRouter({
    history: createWebHistory(),
    routes: [
        {
            path: '/',
            name: 'zhuye',
            component: Home,
        },
        {
            path: '/about',
            name: 'guanyv',
            component: About,
            children:[
                {
                    name:'xijie',
                    path: 'detail',
                    component: Detail
                }
            ]
        },
    ]
})
export default router
  1. 跳转路由(记得要加完整路径):
<router-link to="/about/detail">xxxx</router-link>
<!-- 或 -->
<router-link :to="{path:'/about/detail'}">xxxx</router-link>
  1. 记得去About组件中预留一个<RouterView></RouterView>
<template>
    <div class="about">
        <nav class="about-list">
            <RouterLink v-for="item in List"
                :key="item.id" 
                :to="{path:'/about/detail'}"
            >
                {{ item.title }}
            </RouterLink>
        </nav>
        <div class="about-detail">
            <RouterView></RouterView>
        </div>
    </div>
</template>

1.8. 路由传参

query

  1. 传递参数
<!-- 跳转并携带query参数(to的字符串写法) -->
<RouterLink :to="`/about/detail?id=${item.id}&title=${item.title}&content=${item.content}`">
{{ item.title }}
</RouterLink>
            
<!-- 跳转并携带query参数(to的对象写法) -->
<RouterLink :to="{
        path:'/about/detail',
        query: {
            id: item.id,
            title: item.title,
            content: item.content,
        }
    }">
    {{ item.title }}
</RouterLink>
  1. 接收参数:
import { useRoute } from 'vue-router';
import { toRefs } from 'vue';

let route = useRoute()
let { query } = toRefs(route)

params

路由文件index.ts配置

import { createRouter, createWebHistory } from "vue-router"
import Home from "@/views/Home.vue"
import About from "@/views/About.vue"
import Detail from "@/views/Detail.vue"

const router = createRouter({
    history: createWebHistory(),
    routes: [
        {
            path: '/',
            name: 'zhuye',
            component: Home,
        },
        {
            path: '/about',
            name: 'guanyv',
            component: About,
            children: [
                {
                    name: 'xijie',
                    path: 'detail/:id/:title/:content',
                    component: Detail
                }
            ]
        },
    ]
})
export default router
  1. 传递参数
<!-- 跳转并携带params参数(to的字符串写法) -->
<RouterLink :to="`/about/detail/${item.id}/${item.title}/${item.content}`">{{ item.title }}</RouterLink>
            
<!-- 跳转并携带params参数(to的对象写法) -->
<RouterLink :to="{
    name: 'xijie', //用name跳转
    params: {
        id: item.id,
        title: item.title,
        content: item.content,
    }
    }">
    {{ item.title }}
</RouterLink>
  1. 接收参数:
import { toRefs } from 'vue';
import { useRoute } from 'vue-router';
let route = useRoute()

let { params } = toRefs(route)

备注1:传递params参数时,若使用to的对象写法,必须使用name配置项,不能用path

备注2:传递params参数时,需要提前在规则中占位

// content有就传,无就不传
{
    path: '/about',
    name: 'guanyv',
    component: About,
    children: [
        {
            name: 'xijie',
            path: 'detail/:id/:title/:content?',
            component: Detail
        }
    ]
},

1.9. 路由的props配置

作用:让路由组件更方便的收到参数(可以将路由参数作为props传给组件)

{
	name:'xijie',
	path:'detail/:id/:title/:content',
	component:Detail,

    // props的对象写法,作用:把对象中的每一组key-value作为props传给Detail组件
    // props:{a:1,b:2,c:3}, 

    // props的布尔值写法,作用:把收到了每一组params参数,作为props传给Detail组件
    // props:true
  
    // props的函数写法,作用:把返回的对象中每一组key-value作为props传给Detail组件
    props(route) {
        return route.query
    }
}

1.10. replace属性

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

  2. 浏览器的历史记录有两种写入方式:分别为pushreplace

    • push是追加历史记录(默认值)
    • replace是替换当前记录
  3. 开启replace模式:

<RouterLink replace .......>XXX</RouterLink>

1.11. 编程式导航

路由组件的两个重要的属性:$route$router变成了两个hooks

// <button @click="showAboutDetail(item)">查看</button>

import {useRoute,useRouter} from 'vue-router'

const route = useRoute()
const router = useRouter()

interface AboutInter {
    id: string
    title: string
    content: string
}
function showAboutDetail(item:AboutInter) {
    // router.push()括号填写类型与to一样
    router.push({
        name: 'xijie',
        params: {
            id: item.id,
            title: item.title,
            content: item.content,
        }
    })
}

1.12. 重定向

  1. 作用:将特定的路径,重新定向到已有路由。

  2. 具体编码:

{
    path:'/',
    redirect:'/about'
},
{
    path: '/:catchAll(.*)',
    redirect: '/404/'
}

文章作者: FW
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 FW !
评论
  目录