vue学习(二) 路由器

1.路由rounter的创建步骤

1.主页面区分导航区、展示区,导航区不同的链接点击,展示区展示不同的组件内容。
2.创建路由器,主要是设置路由模式和路由表(路径和组件对应关系)。
3.编写不同组件用于展示区不同的展示内容,vue文件。

2.一个简单的demo

2.1在App.vue中创建导航区和展示区

<template>
      <h1>路由测试</h1>
      <div><!-- 导航区,使用RouterLink跳转-->
        <RouterLink class="router-link" to="/home">首页</RouterLink>
        <RouterLink class="router-link" to="/news">新闻</RouterLink>
        <RouterLink class="router-link" to="/about">关于</RouterLink>
      </div>
      
      <div><!-- 展示区,使用RouterView占位 -->
        <RouterView class="content"></RouterView>
      </div>
</template>

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

</script>

<style scoped>
.router-link{
  height: fit-content;
  width: fit-content;
  margin: 5px 6px;
}
.content{
  height: fit-content;
  widows: 100%;
}

</style>

2.2创建路由器并引入

接下来就是最关键的一步:创建路由器,并引入mian.js。在src目录下,创建一个文件夹,叫router,并创建一个文件index.ts。代码编写如下:

//   router/index.ts

import { createRouter, createWebHistory } from "vue-router";
import Home from "../pages/Home.vue"
import News from "../pages/News.vue"
import About from "../pages/About.vue"

//创建一个路由器
const router = createRouter({
      //模式
      history:createWebHistory(),
      //路由表
      routes:[
            {path:"/home",component:Home},
            {path:"/news",component:News},
            {path:"/about",component:About}
      ]
});

//暴露出去
export default router;

在main.ts代码中挂载到app上:

import { createApp } from 'vue'
import './style.css'
import App from './App.vue'
import router from "./router"

const app = createApp(App)
//挂载 router
app.use(router)
app.mount('#app')

2.3编写各个展示页面

在src目录下,创建一个文件夹,叫components,加入About.vue Home.vue News.vue 供路由组件调用。

<template>
      <div>
            this is Home!
      </div>
</template>
<script lang="ts" setup>
defineOptions({
  inheritAttrs: false
})
</script>
<style></style>

3.两个重要的问题

1.路由组件一般放在page或者view文件夹,一般组件放在components文件夹下面。
2.通过点击导航,消失的组件是被销毁的,而不是被隐藏。再次展示就被再次创建。

对象方案和链接的方式:

<RouterLink active-class="router-link" to="/home">首页</RouterLink>
<RouterLink active-class="router-link" :to='{path:"/news"}'>新闻</RouterLink>
<RouterLink active-class="router-link" to="/about">关于</RouterLink>

5.路由器工作模式

1、hash模式(vue-router默认模式URL后面带#)使用URL的hash值来作为路由,支持所有浏览器 缺点:只能改变#后面的来实现路由跳转。

history: createWebHashHistory(process.env.BASE_URL),

2、history模式(通过mode: 'history’来改变为history模式)HTML5 (BOM)History API 和服务器配置 缺点:怕刷新如果后端没有处理这个情况的时候前端刷新就是实实在在的请求服务器这样消耗的时间很多还很慢。

history: createWebHistory(process.env.BASE_URL),

3、abstract模式适用于所有JavaScript环境,例如服务器端使用Node.js。如果没有浏览器API,路由器将自动被强制进入此模式。

history: createMemoryHistory(process.env.BASE_URL),

6.命名路由

有时候,通过一个名称来标识一个路由显得更方便一些,特别是在链接一个路由,或者是执行一些跳转的时候。你可以在创建 Router 实例的时候,在 routes 配置中给某个路由设置名称。

const router = new VueRouter({
routes: [
{
path: '/user/:userId',
name: 'user',
component: User
}
]
})
要链接到一个命名路由,可以给 router-link 的 to 属性传一个对象:

User
这跟代码调用 router.push() 是一回事:

router.push({ name: 'user', params: { userId: 123 } })
这两种方式都会把路由导航到 /user/123 路径。

7.嵌套路由

当需要有两级路由时,则需要改造路由表,重点在于childre节点,代码如下:

//创建一个路由器
const router = createRouter({
      //模式
      history:createWebHistory(),
      //路由表
      routes:[
            {
                  path:"/home",
                  component:Home
            },
            {
                  path:"/news",
                  component:News,
                  children:[
                        {
                              path:"detail",//子路由前不需要加斜杠 /
                              component:()=> import("../pages/NewDetail.vue")
                        }

                  ]
            },
            {
                  path:"/about",
                  component:About
            }
      ]
});

8.路由传参

//创建一个路由器
const router = createRouter({
      //模式
      history:createWebHistory(),
      //路由表
      routes:[
            { path: '/', redirect: '/home' }, 
            {
                  path:"/home",
                  component:Home
            },
            {
                  name:"/news",
                  path:"/news",
                  component:News,
                  children:[
                        {
                              path:"detail1/:id",//路径字符串 / 拼接参数
                              component:()=> import("../pages/NewDetail.vue")
                        },
                        {
                              name:"detail2",
                              path:"detail2",//路径字符串?拼接参数
                              component:()=> import("../pages/NewDetail.vue")
                        },
                  ]
            },
            {
                  path:"/about",
                  component:About
            }
      ]
});

<template>
      <div>
            path + 占位符---------------------------------------------------------<br/>
            <ul v-for="(item,index) in news">
                  <router-link :to="`/news/detail1/${item.id}`">{{item.title}}</router-link> <br/>   
            </ul>
            path + 占位符 对象的方式---------------------------------------------------------<br/>

            <ul v-for="(item,index) in news">
                  <router-link :to="{
                        path:`/news/detail1/${item.id}`
                  }">
                  {{item.title}}</router-link> <br/>   
            </ul>

            path + ? query 的方式---------------------------------------------------------<br/>

            <ul v-for="(item,index) in news">
                  <router-link :to="`/news/detail2?id=${item.id}`">{{item.title}}</router-link> <br/>   
            </ul>
            path + query---------------------------------------------------------<br/>
            <ul v-for="(item,index) in news">
                  <router-link :to="{
                        path:`/news/detail2`,
                        query:{
                              id:item.id,
                        }
                  }">
                  {{item.title}}</router-link> <br/>   
            </ul>

      </div>
      <div>
            <RouterView></RouterView>
      </div>
</template>
<script lang="ts" setup>
import { reactive,ref } from "vue";

const news = ref(
      [
            {"id":"001","title":"new 1","content":"this is new 1,id is 001."},
            {"id":"002","title":"new 2","content":"this is new 2,id is 002."},
            {"id":"003","title":"new 3","content":"this is new 3,id is 003."},
            {"id":"004","title":"new 4","content":"this is new 4,id is 004."},
            {"id":"005","title":"new 5","content":"this is new 5,id is 005."}
      ]
)

defineOptions({
  inheritAttrs: false
})

</script>
<style></style>
<template>
      <div>
            this is new detail!param id is {{router.params.id}}<br/>
            this is new detail!query id is {{router.query.id}}
      </div>
</template>
<script lang="ts" setup>
import {useRoute} from 'vue-router';
import {
  onBeforeMount,
  onMounted,
  onBeforeUpdate,
  onUpdated,
  onBeforeUnmount,
  onUnmounted,
} from "vue";


const router = useRoute();
const params = router.params;
console.log(params)
defineOptions({
  inheritAttrs: false
})

</script>
<style></style>

9.props

Vue-Router路由的props配置,待补充。

10.replace属性

11.编程式导航

1.push 常用

2.replace 不会在浏览器得历史记录中加,只会替代掉最后一条记录(这个比较好用)

3.go

12.重定向

重定向比较简单,代码如下:

{ path: '/', redirect: '/home' }, 
posted @ 2024-02-02 17:56  身带吴钩  阅读(21)  评论(0编辑  收藏  举报