Vue项目中使用router

Vite项目中使用router的步骤:

1.安装路由器库:

复制代码
 npm install vue-router@4

2.创建路由配置:通常命名为 router.js 或者 router/index.js

复制代码
 import { createRouter, createWebHashHistory } from 'vue-router';
 import Login from '../views/Login.vue';
 import Index from '../views/Index.vue';
 ​
 const routes = [
     {path:'/',component: Login},
     {
         path:'/index', component: Index
         ,children: [
             {
                 path: '',
                 alias: '/list',
                 component: () => import('../components/User.vue')
             },
             {
                 path: '/upload',
                 component: () => import('../components/Avatar.vue')
             }
         ]
     }   
 ]
 ​
 // 创建路由实例
 const router = createRouter({
     routes,
     history: createWebHashHistory()
 });
 ​
 // 导出路由实例
 export default router;

3.在应用中使用路由:通常是 main.js中使用创建的路由实例

复制代码
 import { createApp } from 'vue'
 import ElementPlus from 'element-plus'
 import 'element-plus/dist/index.css'
 import elementIcon from "./plugins/icons";
 import { createPinia } from 'pinia'
 import axios from "axios"
 // import './style.css'
 import router from './router'
 import App from './App.vue'
 ​
 const pinia = createPinia()
 const app = createApp(App);
 ​
 app.use(ElementPlus);
 app.use(router);
 app.use(pinia);
 app.use(elementIcon);
 app.config.globalProperties.$axios = axios
 ​
 app.mount('#app')

4.在组件中使用路由:在模板中使用 <router-link> 来生成链接

复制代码
 <template>
     <!-- 默认显示的是路由中的 / -->
     <router-view></router-view>
 </template>
相关推荐
lecepin33 分钟前
AI Coding 资讯 2025-10-22
前端·javascript·后端
gustt35 分钟前
深入理解 JavaScript 的对象与代理模式(Proxy)
javascript
3秒一个大1 小时前
JavaScript 对象:从字面量到代理模式的灵活世界
javascript
BumBle1 小时前
uniapp AI聊天应用技术解析:实现流畅的Streaming聊天体验(基础版本)
前端·uni-app
搞个锤子哟1 小时前
vant4的van-pull-refresh里的列表不在顶部时下拉也会触发刷新的问题
前端
jnpfsoft1 小时前
低代码视图真分页实操:API/SQL 接口配置 + 查询字段避坑,数据加载不卡顿
前端·低代码
HHHHHY1 小时前
使用阿里lowcode,封装SearchDropdown 搜索下拉组件
前端·react.js
前端付豪1 小时前
万事从 todolist 开始
前端·vue.js·前端框架
小胖霞1 小时前
从零开始:在阿里云 Ubuntu 服务器部署 Node+Express 接口(基于公司 GitLab)
前端·后端
A_Bin1 小时前
前端工程化之【包管理器】
前端