vue(20)路由使用小进阶

主要是深入理解一下上一篇中的router中index.js文件中的代码,上一篇中代码如下:

import { createRouter, createWebHistory } from 'vue-router' import Home from '../views/Home.vue' import About from '../views/About.vue'
const routes = [   {     path: '/',     name: 'Home',     component: Home   },   {     path: '/about',     name: 'About',     component:About   } ]
const router = createRouter({   history: createWebHistory(process.env.BASE_URL),   routes })
export default router 在上面的代码中我们在头部就直接引入了各个路由的组件: import Home from '../views/Home.vue' import About from '../views/About.vue' 这样写后,在项目build之后dist中会将这些不同路由的组件打包到一个js文件中,加载页面的时候,不论你访问哪个路由相当于都要加载这个js文件,如果一个项目有上百个组件,那么访问每个路由的时候都加载所有的路由组件就会让页面显得很卡。 如果希望每个路由打包生成一个自己的js文件,在访问自己路由的时候加载自己的js包,就要改为下面这样的写法: import { createRouter, createWebHistory } from 'vue-router'
const routes = [   {     path: '/',     name: 'Home',     component: ()=>import('../views/Home.vue')//这里改为使用一个箭头函数返回路由的组件   },   {     path: '/about',     name: 'About',     component: ()=>import('../views/About.vue')//这里改为使用一个箭头函数返回路由的组件   } ]
const router = createRouter({   history: createWebHistory(process.env.BASE_URL),   routes })
export default router   下面是理解一下这句代码:history: createWebHistory(process.env.BASE_URL), 这句代码的意思是采用何种模式来设置路由。 这里的模式vue提供了三种还是四种,但是我们常用的就两种,一种就是上面的history模式,这种模式主要是使用浏览器自带的history保存之前浏览的页面的这一系列api来完成前端路由跳转。 另外一种叫hash模式,这个模式的写法如下: import { createWebHashHistory } from 'vue-router' const router = createRouter({   //history: createWebHistory(process.env.BASE_URL),   history:createWebHashHistory(process.env.BASE_URL),//采用hash路由模式   routes }) 这个模式最大的特点是会在浏览器的地址栏的路由前面加上一个“#”,好像是“#”后面的内容在发送服务器请求的时候就不会携带过去。 现在对这两种模式也是没有深入研究,只知道hash模式的地址栏会多出个“#”如果要美观的话就用history模式。后面需要用到的时候在深入研究。
上一篇:【OCP最新题库解析(052)--题2】...is true about FAST_START_MTTR_TARGET


下一篇:react-router-dom 的基本使用