1. 在自己的views文件夹下创建自己的vue页面
2. 在router文件夹下面的index.js中导入自己的页面路径(vite已经默认设置了@为src路径,不需要再写配置文件了)
import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '@/views/Home/index.vue'
import LoginView from '@/views/Login/index.vue'
import Layout from '@/views/Layout/index.vue'
import Category from '@/views/Category/index.vue'
const router = createRouter({
history: createWebHistory(import.meta.env.BASE_URL),
routes: [
{
path: '/',
name: 'layout',
component: Layout,
},
{
path: '/login',
name: 'login',
component: LoginView
}
]
})
export default router
其中routes中的component:后面是上述引入页面路径名称,name相当于mysql建表的备注
3. 我们的路由都要有一个出口,所以要去验证App.vue中有没有<router-view/>,没有的话页面就无法渲染。
至此一级路由设置完毕。
4. 设置二级路由(其实就是在2的基础上添加children路由)
import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '@/views/Home/index.vue'
import LoginView from '@/views/Login/index.vue'
import Layout from '@/views/Layout/index.vue'
import Category from '@/views/Category/index.vue'
const router = createRouter({
history: createWebHistory(import.meta.env.BASE_URL),
routes: [
{
path: '/',
name: 'layout',
component: Layout,
children:[
{
path: '/category',
name: 'category',
component: Category
},
{
path: '/HomeView',
name: 'HomeView',
component: HomeView
}
]
},
{
path: '/login',
name: 'login',
component: LoginView
}
]
})
export default router
5. 你想让二级路由在那个页面同步渲染,就要在4的基础上添加<router-view/>(例如:我想在Layout.vue文件下面同步渲染,那么Layout.vue文件我就要添加<router-view/>)
<template>
<div>
我是Layout
</div>
<router-view></router-view>
</template>
<script setup>
</script>
<style lang="scss" scoped>
</style>