Vue Router

157 阅读2分钟

Vue Router

步骤

  • 安装npm i vue-router
  • 配置router/index.js
//引入
import { createRouter, createWebHashHistory } from "vue-router"
//配置
import Xxx from "../view/color.vue"
const router = createRouter({
    history: createWebHashHistory(),
    routes:[
    {
        path: "/xxx",
        components: Xxx
    }
    ]
})
//导出
export default router
  • 引入在main.ts
import router from "./router/index"

app.use(router)
  • 呈现
    • <router-view/>
    • <RouterView>
  • 切换
    • <router-link to="/">首页</router-link>

路由404

{
    path: "/:pathMatch(.*)*",
    component: () => import("../view/not-fount.vue")
},

两个路由 API

  • $router 路由对象,可以用其提供的方法触发路由跳转
  • $route 专门用于提取路由参数

路由懒加载与实现原理

  • 图片懒加载 (优化首屏访问体验)
  • 路由懒加载(让组件的相关资源在访问对应路由时再加载)
  • 不使用懒加载
    • 项目是 SPA 应用
    • 当项目最终上线后,用户打开首页的一瞬间,会从后端加载项目相关所有页面组件资源
    • 可能会导致首页白屏、首页打开速度慢
    import Home from '../views/Home.vue'
    import Login from '../views/Login.vue'
    
  • 采用懒加载
const Home = ()=>import('../views/Home.vue')
const Login = ()=>import('../views/Login.vue')

路由传参

动态路由传参

  • 设置形参 routes 配置的 path 后面 '/contact/:tel'
  • 传递实参 router-link 的 to 属性中 to="/contact/xxx"
  • 提取使用 在路由跳转的目标组件中
    • template 区域 $route.params
    • script 区域 this.$route.params

query 传参

  • 传递实参 router-link 的 to 属性中 to="/login?name=xxx"
  • 提取使用 在路由跳转的目标组件中
    • template 区域 $route.query
    • script 区域 this.$route.query

嵌套路由

步骤

  • 新建子组件
  • 配置子路由 为主路由添加 children
const routes = [ 
    {
        path: '/user/:id',
        component: User,
        children: [ 
            { 
                path: 'profile',
                component: UserProfile, 
            }
        ]
},
  • 呈现子组件 需要在主组件内添加 router-view
  • 触发跳转

编程式导航

//在script中
//法1
this.$router.push(目标路由路径)

//法2 编程式导航传参
this.$router.push(`/prod/p2?id=123&name=xxx`)

//法3 编程式导航传参,适合携带多个参数
this.$router.push({  //编程式导航传参,适合携带多个参数
   path: `/prod/${target}`,
   query: {
      id: 123,
      name: "xxx",
   },
});

命名路由

  • 为路由添加 name 配置
{
   path:'/p1',
   name:'pp1',
   component:P1
 },
  • 使用 name 触发路由切换
this.$router.push({
 name:'pp1'
})

命名视图

  • 在同一层路由下,使用多个 router-view
<router-view/>
<router-view name="footer"/>
  • 路由对应的组件使用 components 进行配置
{
   path:'/login',
   components:{
     default:Login,
     'footer':Footer
   }
},

重定向和别名

  • 重定向 redirect
{
     path: "/",
     redirect: "/color",
 },
  • 别名 alias
{
  path: "/animal",
  alias: "/",
 }

Hash 模式与 History 模式

history 模式

  • 项目上线的时候,如果后端不协助处理,项目访问会出现 404
http://127.0.0.1:5173/news   vue路由?如果不做特殊配置,会被后端认为是一个数据接口,导致页面出现404
http://localhost:3000/login   数据接口?

hash 模式 【建议使用】

  • 开发跟上线都可以直接使用
http://127.0.0.1:5173/#/news   Hash模式,部署时不会存在访问404问题