首页 > 其他分享 >前端学习-vue视频学习012-路由

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

时间:2024-03-23 23:46:25浏览次数:17  
标签:vue import route 学习 012 path router 路由

尚硅谷视频教程

路由简介

路由就是一组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'
        }
    ]
})

标签:vue,import,route,学习,012,path,router,路由
From: https://www.cnblogs.com/ayubene/p/18088410

相关文章

  • 基于SpringBoot+Vue医疗管理系统设计和实现(源码+LW+部署讲解)
    博主介绍:✌全网粉丝30W+,csdn特邀作者、博客专家、CSDN新星计划导师、Java领域优质创作者,博客之星、掘金/华为云/阿里云/InfoQ等平台优质作者、专注于Java技术领域和学生毕业项目实战,高校老师/讲师/同行前辈交流✌主要内容:SpringBoot、Vue、SSM、HLMT、Jsp、PHP、Nodejs......
  • 基于SpringBoot+Vue新闻管理系统设计和实现(源码+LW+部署讲解)
    博主介绍:✌全网粉丝30W+,csdn特邀作者、博客专家、CSDN新星计划导师、Java领域优质创作者,博客之星、掘金/华为云/阿里云/InfoQ等平台优质作者、专注于Java技术领域和学生毕业项目实战,高校老师/讲师/同行前辈交流✌主要内容:SpringBoot、Vue、SSM、HLMT、Jsp、PHP、Nodejs......
  • 深度学习入门 基于Python的理论与实现
    深度学习入门基于Python的理论与实现感知机由美国学者FrankRosenblatt在1957年提出,是作为神经网络(深度学习)的起源的算法。感知机接收多个输入信号,输出一个信号信号只有0和1两种取值感知机将输入信号乘以相应的权重后求和,若大于阈值则输出1,否则输出0若用\(x_{1},x_{2}\)......
  • 后缀数组学习笔记(未完成
    后缀数组定义与实现定义后缀从字符串某个位置i到字符串末尾的子串,定义s的第i个字符为第一个元素的后缀为suf(i)。后缀数组把s的每一个后缀按照字典序排序,后缀数组sa[i]表示排名为i的后缀的起始位置的下标。rk[i]数组代表起始位置为i的后缀的排名。rk[]和sa[]是一一对应关系......
  • LaTex学习实践(简易快速LaTex上手例子)
    目录前言正文完全参考前言这篇博客完全是博客https://blog.csdn.net/NSJim/article/details/109066847?spm=1001.2014.3001.5506的实践产物因为写的太好了,所以我进行了实践(overleaf平台)所有的代码和图片我已上传,下载后,上传到自己的overleaf平台即可编......
  • vue2 在 main.js 中定义全局函数,在二次封装的 api\index.js 中引用全局函数 GPT4 Tur
    在Vue2中,你可以通过Vue的原型系统来定义全局函数,然后在整个应用的任何组件中使用这些函数。同样,你也可以在其他JavaScript文件中使用这些函数,比如你提到的二次封装的API文件。下面是如何实现这一过程的步骤:###第一步:在`main.js`中定义全局函数在Vue项目的入口文件`main.js`中,你......
  • 【离散数学-学习日记】2024-3-23
    有向欧拉图的判别法【定理4-3】有向图D是欧拉图当且仅当D是强连通的且每个顶点的入度都等于出度。【定理4-4】有向图D是半欧拉图当且仅当D是单向连通的,且D中恰好有两个奇度顶点,其中一个的入度比出度大1,另一个的出度比入度大1,而其余顶点的入度都等于出度。【定理4-5】G是......
  • vue3 动态编译组件失败:Component provided template option but runtime compilation
    根据vue3官方文档路由,写了如下一个简单的页面来模拟路由的实现。为了减少*.vue文件的个数,在这个但页面中,使用defineComponent通过object定义组件。<scriptsetup>import{ref,computed,defineComponent}from'vue'constHome=defineComponent({template:`......
  • 基于java+springboot+vue实现的游戏账号估价交易平台(文末源码+Lw+ppt)23-555
    摘 要系统根据现有的管理模块进行开发和扩展,采用面向对象的开发的思想和结构化的开发方法对游戏账号估价交易的现状进行系统调查。采用结构化的分析设计,该方法要求结合一定的图表,在模块化的基础上进行系统的开发工作。在设计中采用“自下而上”的思想,在游戏账号估价交易平台......
  • 基于java+springboot+vue实现的外卖平台系统(文末源码+Lw+ppt)23-568
    摘 要伴随着我国社会的发展,人民生活质量日益提高。于是对外卖平台系统进行规范而严格是十分有必要的,所以许许多多的信息管理系统应运而生。此时单靠人力应对这些事务就显得有些力不从心了。所以本论文将设计一套外卖平台系统,帮助商家进行菜品分类、菜品信息、订单等繁琐又重......