首页 > 其他分享 >vue学习(二) 路由器

vue学习(二) 路由器

时间:2024-02-02 18:00:53浏览次数:44  
标签:vue import 学习 path router id 路由 路由器

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' }, 

标签:vue,import,学习,path,router,id,路由,路由器
From: https://www.cnblogs.com/chenjie0949/p/18003615

相关文章

  • 学习AJAX时出现has been blocked by CORS policy: Cross origin requests are only su
    练习js时用到ajax,console报错:AccesstoXMLHttpRequestat‘file:///Users/XXX/Downloads/nav/nav.json’fromorigin‘null’hasbeenblockedbyCORSpolicy:Crossoriginrequestsareonlysupportedforprotocolschemes:http,data,chrome,chrome-extension,chro......
  • Python学习笔记04
    3.3运算符(以下假设变量a=10,变量b=21)【算数运算符】:运算符描述实例+加,两个对象相加a+b输出结果31-减,得到负数或是一个数减去另一个数a-b输出结果-11*乘,两个数相乘或是返回一个被重复若干次的字符串a*b输出结果210/除,x除......
  • Python学习笔记02
    二、基础语法2.1注释单行注释:#多行注释:'''或"""示例输入:#第一个注释#第二个注释'''第三注释第四注释'''"""第五注释第六注释"""print("Hello,World!")输出:Hello,World!2.2行与缩进pyt......
  • Python学习笔记03
    3.2Number(数字)三种数值类型实例:整型(int)浮点型(float)复数(complex)100.03+4j10015.2045.j-786-21.93e+26J080-90.4.53e-7j-049032.3e+183.14j-0x26070.2E-12a+bj↑0x表示16进制↑e和E为科学计数法↑a,b均为浮点型数字类型转......
  • (数据科学学习手札158)基于martin为在线地图快速构建精灵图服务
    本文示例代码已上传至我的Github仓库https://github.com/CNFeffery/DataScienceStudyNotes1简介大家好我是费老师,martin作为快速发展中的新一代开源高性能地图服务框架,在之前的两篇文章中,我已为大家分别介绍过使用martin快速发布矢量切片地图服务(https://www.cnblogs.co......
  • 盘点那些硬件+项目学习套件:Hi3861鸿蒙开发板及入门常见问题解答
    华清远见20岁了~过去3年里,华清远见研发中心针对个人开发板业务,打造了多款硬件+项目学习套件,涉及STM32单片机、嵌入式、物联网、人工智能、鸿蒙、ESP32、阿里云IoT等多技术方向。今天我们来盘点一下,比较受欢迎几款“硬件+项目”学习套件,以及一些初学者比较关注的问题。盘点二:Hi3861......
  • 龙年-2月学习到的新知识
    数据库时间类型字段精度问题DatetimeTimestamp保存毫秒防止精度丢失数据库字段为DATETIME(3)时可以保存毫秒。当数据库为MariaDb10.x.x,则需要jdbc驱动需更换为mariadbconnnector,或者Mariadb相应Mysql数据库版本高于5.6.4则无需更改。DATETIME(3)对应的Java类型,......
  • vue中的响应式和react中的响应式一样吗?
    Vue.js和React在实现响应式原理上有所不同:Vue.js的响应式机制:依赖收集(DependentDataCollection):Vue使用了基于getter/setter的Object.defineProperty()方法,对数据对象的属性进行拦截。当一个组件渲染时,Vue能够跟踪到模板中哪些数据被访问(getter),并记录下它们之间的......
  • erlang学习笔记一
    Elang是一种函数式编程语言,具有一些独有的数据类型和数据结构.以下是Erlang中的常见数据类型和数据结构.1.Atom(原子):Atom是一个不可变的符号常量,用于表示标识符和常量.Atom以小写字符开头,可以包含字母,数字,下划线和@符号.例如:ok,hello,true。2.NUmber(数字):数字可以是......
  • github下载Vue-Devtools进行安装的方式
    注意:下载Vue-Devtools依赖需要yarn环境.0.安装:yarnnpminstallyarn-g配置:下载镜像1.在C盘目录下,打开.yarnrc环境配置文件2.复制下面命令到配置文件registry"https://registry.npmmirror.com"chromedriver_cdnurl"https://npmmirror.com/mirrors/chromedriver/"elect......