前端学习-vue视频学习012-路由

尚硅谷视频教程

路由简介

路由就是一组key-value的对应关系
多个路由,需要经过路由器的管理

怎样才能使用路由器

  • 安装路由器 npm i vue-router
  • 在src内新增文件夹router
  • 在router文件夹新增文件index.ts,在其中创建路由器并暴露出去
// 创建一个路由 并暴露出去

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

// 引入可能要呈现的组件
import Home from "@/components/Home.vue";
import About from "@/components/About.vue";
import News from "@/components/News.vue";

// 创建路由器
const router = createRouter({
    history:createWebHistory(),
    routes: [
        {
            path:'/home',
            component: Home
        },
        {
            path:'/about',
            component: About
        },
        {
            path:'/news',
            component: News
        },
    ]
})

// 暴露出去
export default router

基本切换操作

首先在main.ts中使用路由器

// 引入createApp创建应用
import { createApp } from "vue";
//  引入APP根组件
import App from './App.vue'

// 引入路由器
import router from "./router";
// 创建一个应用
const app = createApp(App)
// 使用路由器
app.use(router)
// 挂载应用到app容器
app.mount('#app')

在App.vue中引入RouterView,用于设置页面放置位置

<script lang="ts" setup name="App">
    import { RouterView,RouterLink } from 'vue-router'
</script>

<template>
    <div class="app">
        <h2>vue route test</h2>
        <div class="content">
            <RouterView></RouterView>
        </div>
    </div>
</template>

在App.vue中引入RouterLink,绑定页面和导航,确保点击导航栏时链接到对应的路径

<script lang="ts" setup name="App">
    import { RouterView,RouterLink } from 'vue-router'
</script>

<template>
    <div class="app">
        <h2>vue route test</h2>
        <div class="nav">
            <RouterLink to="/home" active-class="active">首页</RouterLink>
            <RouterLink to="/about" active-class="active">关于</RouterLink>
            <RouterLink to="/news" active-class="active">新闻</RouterLink>
        </div>
        <div class="content">
            <RouterView></RouterView>
        </div>
    </div>
</template>

使用active-class,实现点击时展示不同的效果

使用路由的注意点

  • 路由组件通常存放在pagesviews文件夹,一般的则存放在components文件夹
  • 路由组件,指不会自己去写组件标签的组件;一般组件,需要自己写组件标签
  • 通过点击导航,视觉上消失的组件,默认是卸载的,只有重新点击对应导航栏时才挂载

路由器的工作模式

  • history:url更美观,但是需要服务端配合处理路径-toC使用较多
  • hash:url中带#,SEO优化差;但服务端无需处理-后台管理项目使用较多

to的两种写法

<RouterLink to="/about" active-class="active">关于</RouterLink>
<RouterLink :to="{ path:'/news' }" active-class="active">新闻</RouterLink>
<template>
    <div class="app">
        <Header/>
        <div class="nav">
            <RouterLink to="/home" active-class="active">首页</RouterLink>
            <RouterLink to="/about" active-class="active">关于</RouterLink>
            <RouterLink :to="{ path:'/news' }" active-class="active">新闻</RouterLink>
        </div>
        <div class="content">
            <RouterView></RouterView>
        </div>
    </div>
</template>

命名路由

给路由新增name属性

// router/index.ts
const router = createRouter({
    history:createWebHistory(),
    routes: [
        {
            name:'/nameHome',
            path:'/home',
            component: Home
        },
        {
            name:'/nameAbout',
            path:'/about',
            component: About
        },
        {
            path:'/news',
            component: News
        },
    ]
})

使用的时候

<RouterLink :to="{ name:'/about' }" active-class="active">关于</RouterLink>

嵌套路由

新增.vue文件,填写嵌套内容

<template>
    <ul class="news-list">
        <li>编号:</li>
        <li>标题:</li>
        <li>内容:</li>
    </ul>
</template>

<style>
</style>

配置嵌套路由:在原有路由中增加children属性,添加path和component(此处path内容不需要带'/')

// 创建路由器
const router = createRouter({
    history:createWebHistory(),
    routes: [
        {
            path:'/news',
            component: News,
            children:[
                {
                    path:'detail',
                    component:Detail
                }
            ]
        },
    ]
})

index.ts

// 创建一个路由 并暴露出去

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

// 引入可能要呈现的组件
import Home from "@/views/Home.vue";
import About from "@/views/About.vue";
import News from "@/views/News.vue";
import Detail from "@/views/Detail.vue";

// 创建路由器
const router = createRouter({
    history:createWebHistory(),
    routes: [
        {
            name:'/nameHome',
            path:'/home',
            component: Home
        },
        {
            name:'/nameAbout',
            path:'/about',
            component: About
        },
        {
            path:'/news',
            component: News,
            children:[
                {
                    path:'detail',
                    component:Detail
                }
            ]
        },
    ]
})

// 暴露出去
export default router

在需要嵌套的路由组件中使用嵌套路由

<!-- 展示-->
<div class="news-content">
    <RouterView></RouterView>
</div>

传参:query和params

query

传递参数

<!-- 写法1 -->
<!-- <RouterLink :to="`/news/detail?id=${news.id}&title=${news.title}&content=${news.content}`">{{ news.id }}</RouterLink> -->
<!-- 写法2 -->
<RouterLink :to="{
    path:'/news/detail',
    query:{
        id:news.id,
        title:news.title,
        content:news.content,
    }
}">{{ news.id }}</RouterLink>

使用参数

<template>
    <ul class="news-list">
        <li>编号:{{ route.query.id }}</li>
        <li>标题:{{ route.query.title }}</li>
        <li>内容:{{ route.query.content }}</li>
    </ul>
</template>

省略route使用参数(解构route中的query时,要注意如果直接解构会失去响应式,因此要使用toRefs)

<template>
    <ul class="news-list">
        <li>编号:{{ query.id }}</li>
        <li>标题:{{ query.title }}</li>
        <li>内容:{{ query.content }}</li>
    </ul>
</template>

<script setup>
    import { toRefs } from 'vue'
    import { useRoute } from 'vue-router'
    const route = useRoute()
    const { query } = toRefs(route)
</script>
params

配置路由时配置好要传的参数名,如果参数名后加? 代表可传可不传

{
    path:'/news',
    component: News,
    children:[
        {
            name:'detail',
            path:'detail/:id/:title/:content?',
            component:Detail
        }
    ]
}

传参,此处使用方法2传参是,要注意不能使用path,只能使用name;同时传的参数有局限性,不能传数组、对象

<template>
    <div class="news">
        <!-- 导航 -->
        <ul class="news-nav">
            <li v-for="news in newsList">
                <!-- 写法1 -->
                <!-- <RouterLink :to="`/news/detail/${news.id}/${news.title}/${news.content}`">{{ news.id }}</RouterLink> -->
                <!-- 写法2 -->
                <RouterLink :to="{
                    name:'detail',
                    params:{
                        id:news.id,
                        title:news.title,
                    }
                }">{{ news.id }}</RouterLink>
            </li>
        </ul>
        <!-- 展示 -->
        <div class="news-content">
            <RouterView></RouterView>
        </div>
    </div>
</template>

路由的props配置

写法1 将路由收到的所有params参数作为props传给路由组件

  • 在路由配置处,增加props:true
{
    path:'/news',
    component: News,
    children:[
        {
            name:'detail',
            path:'detail/:id/:title/:content?',
            component:Detail,
            // 方法1
            props:true
        }
    ]
}
  • 在路由组件中使用defineProps,填写对应参数名,并直接使用
<template>
    <ul class="news-list">
        <!-- <li>编号:{{ route.params.id }}</li>
        <li>标题:{{ route.params.title }}</li>
        <li>内容:{{ route.params.content }}</li> -->
        <li>编号:{{ id }}</li>
        <li>标题:{{ title }}</li>
        <li>内容:{{ content }}</li>
    </ul>
</template>
<script setup>
    import { defineProps } from 'vue'
    defineProps(['id','title','content'])
</script>

写法2:函数写法:自己决定将什么参数作为props传递给路由组件

  • 配置路由
{
    path:'/news',
    component: News,
    children:[
        {
            name:'detail',
            path:'detail',
            component:Detail,
            // 方法1
            // props:true
            // 方法2
            props(route) {
                return route.query
            }
        }
    ]
}
  • 传参
<RouterLink :to="{
                    name:'detail',
                    // path:'news/detail',
                    query:{
                        id:news.id,
                        title:news.title,
                        content:news.content,
                    }
                }">{{ news.id }}</RouterLink>
  • 使用参数
    <ul class="news-list">
        <!-- <li>编号:{{ route.params.id }}</li>
        <li>标题:{{ route.params.title }}</li>
        <li>内容:{{ route.params.content }}</li> -->
        <li>编号:{{ id }}</li>
        <li>标题:{{ title }}</li>
        <li>内容:{{ content }}</li>
    </ul>
</template>

<script setup>
    // import { toRefs } from 'vue'
    // import { useRoute } from 'vue-router'
    // const route = useRoute()
    // const { query } = toRefs(route)

    // import { useRoute } from 'vue-router'
    // const route = useRoute()

    import { defineProps } from 'vue'
    defineProps(['id','title','content'])
</script>

写法3:对象写法:自己决定将什么参数作为props传递给路由组件,但有局限性

{
    name:'detail',
    path:'detail',
    component:Detail,
    // 方法1
    // props:true
    // 方法2
    props(route) {
        return route.query
    }
    // 方法3
    props:{
        a:111,
        b:222,
        c:333,
    }
}

路由操作浏览器历史记录的动作 push和replace

push

默认是push,每次操作都会记录,可以实现前进后退

replace

直接覆盖掉上一条记录
使用方法

<template>
    <div class="app">
        <Header/>
        <div class="nav">
            <RouterLink replace to="/home" active-class="active">首页</RouterLink>
            <RouterLink replace :to="{ name:'/nameAbout' }" active-class="active">关于</RouterLink>
            <RouterLink replace :to="{ path:'/news' }" active-class="active">新闻</RouterLink>
        </div>
        <div class="content">
            <RouterView></RouterView>
        </div>
    </div>
</template>

编程式路由导航

简单的一个例子

首页挂载3秒后,跳转至新闻页

  • 使用useRouter获取到路由器
  • 使用router.push或router.replace就可以在对应条件下跳转到对应页面
// Home.vue
<template>
    <img src="../img/537.png" alt="">
</template>

<script setup>
    import { onMounted } from 'vue'
    import { useRouter } from 'vue-router'
    const router = useRouter()
    onMounted(() => {
        setTimeout(() => {
            router.push('/news')
        }, 3000);
    })
</script>

<style>
    img {
        width: 200px;
        margin: 0 auto;
    }

</style>

更复杂的例子

点击按钮,跳转到对应页面
在push内的填写方式,和RouterLink内to的填写方式一模一样

  • 新增按钮
<!-- 导航 -->
<ul class="news-nav">
    <li v-for="news in newsList">
        <button @click="changePage(news)">查看</button>
        <RouterLink :to="{
            name:'detail',
            // path:'news/detail',
            query:{
                id:news.id,
                title:news.title,
                content:news.content,
            }
        }">{{ news.id }}</RouterLink>
    </li>
</ul>
  • 新增函数
function changePage(news) {
    router.push({
        name:'detail',
        // path:'news/detail',
        query:{
            id:news.id,
            title:news.title,
            content:news.content,
        }
    })
}

重定向

在router中配置,默认跳转到配置的页面

const router = createRouter({
    history:createWebHistory(),
    routes: [
        {
            path:'/',
            redirect:'/home'
        }
    ]
})
posted @   ayubene  阅读(10)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
点击右上角即可分享
微信分享提示