1.安装路由
npm install vue-router@4
2.在src文件中创建一个views文件夹,在该文件下分别创建Layout和Login文件夹,然后在这两个文件夹里面分别创建index.vue文件
//Layout文件夹的index.vue
<template>
<h1>我是首页</h1>
</template>
//Logint文件夹的index.vue
<template>
<h1>我是登录页</h1>
</template>
3.在src文件夹新建一个router文件夹,在该文件夹下新建index.js文件。在index.js中引入vue-router中的createRouter 和 createWebHashHistory 方法,引入页面文件
// createRouter:创建router实例对象
// createWebHistory:创建history模式的路哟
// 导入页面实例组件
import { createRouter, createWebHistory } from 'vue-router'
import Login from '@/views/Login/index.vue'
import Layout from '@/views/Layout/index.vue'
4.继续在上一步的index.js文件中使用createRouter创建路由实例,并配置路由模式和上面定义的路由规则,并导出router
const router = createRouter({
history: createWebHistory(import.meta.env.BASE_URL),
// routes是配置path和component对应关系的位置
routes:[
{
path : '/',
component : Layout
},
{
path: '/login',
component: Login
}
]
})
// 导出router实例
export default router
5.注册路由:在main.js中导入上面创建的路由文件,并使用app.use注册路由
import router from './router'
createApp(App).use(router).mount('#app');
6.在App.vue文件中渲染组件(一级路由)
<template>
<RouterView />
</template>
7.终端输入命令运行看成果
npm run dev
8.打开这个链接,就可以看到Layout.vue里面的内容
9.在原网址后面加上 /login,就可以看到Login.vue里面的内容
10.如果配置二级路由,同样在view文件夹下新建下图的文件夹和文件,填写内容
11.同样在router文件夹的index.js文件导入页面组件,因为这两个二级路由是在首页(Layout)的,所有配置路由关系要在Layout后新增children。默认二级路由的path配置项置空
import Category from '@/views/Category/index.vue'
import Home from '@/views/Home/index.vue'
//完整路由配置代码
routes:[
{
path : '/',
component : Layout,
children :[
{
//Home是默认,所以path为空
path:'',
component:Home
},
{
path :'category',
component :Category
}
]
},
{
path: '/login',
component: Login
}
]
12.最后渲染组件是在Layout文件夹下的index.vue文件中渲染
<template>
<h1>我是首页</h1>
<!-- 二级路由出口 -->
<RouterView />
</template>
13.最后运行看结果