vue 路由2

  • 路由配置文件(./router/index.ts) :

    // import {createRouter,createWebHashHistory} from 'vue-router'
    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:createWebHashHistory(),
    history:createWebHistory(),
    routes:[
    {
    path:'/home',
    component:Home
    },
    {
    path:'/news',
    component:News
    },
    {
    path:'/about',
    component:About
    }
    ]
    })
    export default router

  • main.ts 代码:

    import { createApp } from 'vue'
    import App from './App.vue'

    import router from './router/index'
    let app = createApp(App)
    app.use(router)
    app.mount('#app')

  • App.vue 代码:

    <template>

    Vue路由测试

    <RouterLink to="/home" active-class="active">首页</RouterLink> <RouterLink to="/news" active-class="active">新闻</RouterLink> <RouterLink to="/about" active-class="active">关于</RouterLink>
    <RouterView></RouterView>
    </template> <script lang="ts" setup name="App"> import {RouterLink,RouterView} from 'vue-router' </script> <style scoped lang="less"> .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. 路由组件通常存放在pagesviews文件夹,一般组件通常存放在components文件夹。

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

路由器工作模式:

Vue 路由器(Vue Router)是 Vue.js 的官方路由管理器,它允许你构建单页面应用(SPA)。在 Vue 路由器中,有两种主要的路由模式:hash 模式和 history 模式。

1. Hash 模式

hash 模式下,路由的 URL 会包含一个 # 符号,后面跟着的是路由的路径。例如,URL 可能是这样的:http://example.com/#/user/id

‌**优点:**‌

  • URL 中 # 符号之前的部分不会被发送到服务器。
  • 它不需要任何服务器端的配置。
  • 它支持所有浏览器。

‌**缺点:**‌

  • URL 中包含 # 符号,不够美观。

  • 它不利于 SEO(搜索引擎优化),因为搜索引擎可能会忽略 # 符号之后的内容。

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

2. History 模式

history 模式下,URL 看起来就像是普通的路径,例如:http://example.com/user/id。这是通过 HTML5 History API 实现的。

‌**优点:**‌

  • URL 看起来更美观,没有 # 符号。
  • 它有利于 SEO,因为完整的 URL 会被发送到服务器。

‌**缺点:**‌

  • 需要服务器端的正确配置来支持,否则刷新页面时会返回 404 错误。

  • 它不支持所有浏览器(特别是 IE9 及以下版本)。

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

服务器配置(对于 History 模式)

如果你选择使用 history 模式,你需要在服务器上做一些配置,以确保当用户直接访问一个路由(例如,输入 URL 或刷新页面时),服务器能够正确地响应。以下是一些常见的服务器配置示例:

Nginx:

复制代码
location / {
  try_files $uri $uri/ /index.html;
}

to的两种写法:

复制代码
  <!-- 第一种写法 -->
      <RouterLink to="/home" active-class="active">首页</RouterLink>
      <!-- 第二种写法 -->
      <RouterLink :to="{path:'/news'}" active-class="active">新闻</RouterLink>

嵌套路由

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

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

    const router = createRouter({
    history:createWebHistory(),
    routes:[
    {
    name:'zhuye',
    path:'/home',
    component:Home
    },
    {
    name:'xinwen',
    path:'/news',
    component:News,
    children:[
    {
    name:'xiang',
    path:'detail',
    component:Detail
    }
    ]
    },
    {
    name:'guanyu',
    path:'/about',
    component:About
    }
    ]
    })
    export default router

3.路由跳转:

复制代码
<router-link to="/news/detail">xxxx</router-link>
<!-- 或 -->
<router-link :to="{path:'/news/detail'}">xxxx</router-link>

4.Home组件中预留一个<router-view>

复制代码
<template>
  <div class="news">
    <nav class="news-list">
      <RouterLink v-for="news in newsList" :key="news.id" :to="{path:'/news/detail'}">
        {{news.name}}
      </RouterLink>
    </nav>
    <div class="news-detail">
      <RouterView/>
    </div>
  </div>
</template>

路由传参

query参数

  1. 传递参数

    复制代码
    <!-- 跳转并携带query参数(to的字符串写法) -->
    <router-link to="/news/detail?a=1&b=2&content=欢迎你">
    	跳转
    </router-link>
    				
    <!-- 跳转并携带query参数(to的对象写法) -->
    <RouterLink 
      :to="{
        //name:'xiang', //用name也可以跳转
        path:'/news/detail',
        query:{
          id:news.id,
          title:news.title,
          content:news.content
        }
      }"
    >
      {{news.title}}
    </RouterLink>
  2. 接收参数:

    复制代码
    import {useRoute} from 'vue-router'
    const route = useRoute()
    // 打印query参数
    console.log(route.query)

params参数

  1. 传递参数

    复制代码
    <!-- 跳转并携带params参数(to的字符串写法) -->
    <RouterLink :to="`/news/detail/001/新闻001/内容001`">{{news.title}}</RouterLink>
    				
    <!-- 跳转并携带params参数(to的对象写法) -->
    <RouterLink 
      :to="{
        name:'xiang', //用name跳转
        params:{
          id:news.id,
          title:news.title,
          content:news.title
        }
      }"
    >
      {{news.title}}
    </RouterLink>
  2. 接收参数:

    复制代码
    import {useRoute} from 'vue-router'
    const route = useRoute()
    // 打印params参数
    console.log(route.params)

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

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

路由的props配置

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

复制代码
{
	name:'xiang',
	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
  }
}

replace属性

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

复制代码
import {useRoute,useRouter} from 'vue-router'

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

console.log(route.query)
console.log(route.parmas)
console.log(router.push)
console.log(router.replace)

编程式导航

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

复制代码
import {useRoute,useRouter} from 'vue-router'

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

console.log(route.query)
console.log(route.parmas)
console.log(router.push)
console.log(router.replace)

重定向

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

  2. 具体编码:

    复制代码
    {
        path:'/',
        redirect:'/about'
    }
相关推荐
zlpzlpzyd18 小时前
vue.js 3中全局组件和局部组件的区别
前端·javascript·vue.js
浩星19 小时前
css实现类似element官网的磨砂屏幕效果
前端·javascript·css
一只小风华~19 小时前
Vue.js 核心知识点全面解析
前端·javascript·vue.js
2022.11.7始学前端19 小时前
n8n第七节 只提醒重要的待办
前端·javascript·ui·n8n
SakuraOnTheWay19 小时前
React Grab实践 | 记一次与Cursor的有趣对话
前端·cursor
阿星AI工作室19 小时前
gemini3手势互动圣诞树保姆级教程来了!附提示词
前端·人工智能
徐小夕19 小时前
知识库创业复盘:从闭源到开源,这3个教训价值百万
前端·javascript·github
xhxxx19 小时前
函数执行完就销毁?那闭包里的变量凭什么活下来!—— 深入 JS 内存模型
前端·javascript·ecmascript 6
StarkCoder19 小时前
求求你试试 DiffableDataSource!别再手算 indexPath 了(否则迟早崩)
前端
fxshy19 小时前
Cursor 前端Global Cursor Rules
前端·cursor