Vue vue-router 路由创建并使用
vue-router说明
Vue Router 是Vue.js官方的路由管理器。它和Vue.js的核心深度集成,让构建单页面应用变得易如反掌。包含功能有:
- 嵌套的路由/视图表
- 模块化的、基于组件的路由配置
- 路由参数、查询、通配符
- 基于Vue.js过度系统的视图过度效果
- 细粒度的导航控制
- 带有自动激活的CSS class 的链接
- HTML5 历史模式或hash模式,在IE6中自动降级
- 自定义的滚动条行为
安装
vue-router是一个插件包,所以我们还是需要用 npm/cnpm进行安装。
npm install vue-router --save-dev
在一个模块化工程中使用它,必须通过 Vue.use(“路由名称”) 明确地安装路由功能
vue-router使用
1.在src文件夹下建立components组件文件夹,分别建立Comtent.vue和Main.vue两个组件
<template> <h1>内容页</h1> </template> <script> export default { name: "Content" } </script> <style scoped> </style>
<template> <h1>首页</h1> </template> <script> export default { name: "Main" } </script> <style scoped> </style>
2.在src文件夹下建立router文件夹,在文件夹下建立 index.js用于路由页面的跳转配置
import Vue from 'vue' import VueRouter from 'vue-router' //导入自定义组件 import Content from '../components/Content' import Main from '../components/Main' //安装路由,显示引用 Vue.use(VueRouter); //配置导出路由 export default new VueRouter({ routes:[ { //路由路径 path:'/content', //自定义路由名称 name:'content', //路由跳转的组件 component:Content }, { //路由路径 path:'/main', //自定义路由名称 name:'main', //路由跳转的组件 component:Main } ] });
3.在main.js中引用自定义路由配置并开启
import Vue from 'vue' import App from './App' import router from './router'//导入自定义路由配置 new Vue({ el: '#app', //配置路由 router, components: { App }, template: '<App/>' })
4.在App.vue中配置并测试路由,主要利用<router-link to="/路由配置中的path">XX</router-link>
<template> <div id="app"> <router-link to="/main">首页</router-link> <router-link to="/content">内容页</router-link> <router-view></router-view> </div> </template> <script> export default { name: 'App' } </script> <style> #app { font-family: 'Avenir', Helvetica, Arial, sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; text-align: center; color: #2c3e50; margin-top: 60px; } </style>
注意:<router-link> 和<router-view>两个标签缺一不可
目录结构如图:
测试结果如图:
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!