npm install vue-router@4 --save
对应vue3.x版本
(1)在router文件下创建index.js文件
(2)文件内导入路由插件vue-router
import {createRouter, createWebHashHistory, createWebHistory} from "vue-router"
(3)index.js文件中配置路规则
- import News from '@/comcomponents/news.vue' // 引入news组件, @相当于src文件夹
- const routes=[
-
- { path:'/'
- component:News //这种方法就需要先引入该组件
-
- },
-
- { path:'/login'
- component:()=>import('@/components/login.vue') //懒加载写法,不进行初始化加载,用到该组件在加载
-
- },
-
- ]
(4)index.js文件中创建路由对象,并暴露
- const router=creatRouter({
-
- history: createWebHashHistory, //也可以写createWebHistory,定义路由模式
- routes //定义的路由规则
-
- })
-
- export default router
(5)main.js入口文件中集成路由插件到vue
- //先引入暴露的router对象
- import router from './index.js' //路径根据实际情况调整
-
- //集成插件
- app.use(router)
(6)路由输出组件设置:一般在App.vue文件内