VueRouter
- Vue-Router官网;
vue-router是vue.js官方给出的路由解决方案,能够轻松的管理SPA项目中组件的切换;- 安装:
yarn add vue-router@4;
快速使用
1.1 创建路由模块
- 在项目中的
src文件夹中创建一个router文件夹,在其中创建index.js模块; - 采用
createRouter()创建路由,并暴露出去; - 在
main.js文件中初始化路由模块app.use(router) - 示例代码:
router/index.js:
import { createRouter } from 'vue-router'// TODO 创建路由 const router = createRouter({// 相关配置 })export default routermain.js:
import { createApp } from 'vue' import App from './App.vue' import router from './router' // 引入路由模块 let app = createApp(App)app.use(router) // 初始化路由插件app.mount('#app')
1.2 规定路由模式
hsitory路由模式可采用:createWebHashHistory():hash模式:- 它在内部传递的实际
URL之前使用了一个哈希字符#; - 由于这部分
URL从未被发送到服务器,所以它不需要在服务器层面上进行任何特殊处理;
- 它在内部传递的实际
createWebHistory():history模式,推荐使用;- 当使用这种历史模式时,
URL会看起来很正常(URL中不带#号); - 由于我们的应用是一个单页的客户端应用,如果没有适当的服务器配置,用户在浏览器中直接访问
URL,就会得到一个404错误,要解决这个问题,你需要做的就是在你的服务器上添加一个简单的回退路由,如果URL不匹配任何静态资源,它应提供与你的应用程序中的index.html相同的页面;
- 当使用这种历史模式时,
- 示例代码:
history路由模式:import { createRouter, createWebHashHistory, createWebHistory } from 'vue-router'// TODO 创建路由 const router = createRouter({// TODO 规定路由模式history: createWebHistory(), })export default routerhash路由模式:import { createRouter, createWebHashHistory, createWebHistory } from 'vue-router'// TODO 创建路由 const router = createRouter({// TODO 规定路由模式history: createWebHashHistory(), })export default router
1.3 使用路由规则
routes配置路由规则:path:路由匹配的URL;name:当路由指向此页面时显示的名字;component:路由调用这个页面时加载的组件;
- 路由模块用到的组件:
HomeVue.vue:<script setup> import { ref, reactive, computed, onMounted } from 'vue'onMounted(() => {}); </script><template><div class="home">网站首页界面</div> </template><style scoped> .home {color: #fff;font-size: 24px;background-color: #ff0040; } </style>BlogHomeVue.vue:<script setup> import { ref, reactive, computed, onMounted } from 'vue'onMounted(() => {}); </script><template><div class="blog-home">博客首页界面</div> </template><style scoped> .blog-home {color: #fff;font-size: 24px;background-color: chartreuse; } </style>
- 创建路由规则数组并使用:
import { createRouter, createWebHashHistory, createWebHistory } from 'vue-router'// TODO 创建路由规则数组 const routes = [{path: '/home',name: 'home',component: () => import('@/views/HomeVue.vue')},{path: '/blog',name: 'blog',component: () => import('@/views/BlogHomeVue.vue')} ]// TODO 创建路由 const router = createRouter({// TODO 规定路由模式history: createWebHistory(),routes })export default router
1.4 声明路由链接(RouterLink) 和 路由出口(RouterView)
- 在组件模块中声明路由链接和占位符:
<router-link></router-link>:路由链接,to属性则为点击此元素,需要切换的路由地址;- 🔺 注意:
- 如果需要配合激活类名使用,需要使用
active-class进行指定;
<router-link to="路径" active-class="类名" > xxx </router-link> - 如果需要配合激活类名使用,需要使用
- 🔺 注意:
<router-view />:路由占位符(Vue2中的路由出口),路由切换的视图展示的位置;
- 示例代码:
App.vue:(此处有可能URL地址中仍然带有#号,需要重启项目)<script setup> import { ref, reactive, computed, onMounted } from 'vue'onMounted(() => {}); </script><template> <!-- 路由链接,点击是路由地址会切换到属性 to 的地方 --><router-link to="/home">首页</router-link> | <router-link to="/blog">博客</router-link><hr><!-- 路由试图,路由切换组件展示的地方,路由出口 --><router-view /> </template>
- 最终运行展示:
