路由
页面路由
import { createRouter, createWebHashHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'
import DomeView from '../views/DomeView.vue'
const router = createRouter({
history: createWebHashHistory(import.meta.env.BASE_URL),
routes: [
{
path: '/',
name: 'home',
component: HomeView
},
{
path: '/about',
name: 'about',
// route level code-splitting
// this generates a separate chunk (About.[hash].js) for this route
// which is lazy-loaded when the route is visited.
component: () => import('../views/AboutView.vue')
},
{
path:'/dome',
name:'dome',
component:DomeView
},
{
path:'/stu/:id/:name/:sex',
name:'stu',
component:()=>import('../views/StuDView.vue'),
children:[
{
//子路由不能加斜杠
path:'chengji',
component:()=>import("../views/StuChengJi.vue")
},
{
path:'dangan',
component:()=>import('../views/StuDangAn.vue')
}
]
},
{
path:'/studd/:id',
name:'studd',
component:()=>import('../views/StuDDDView.vue')
}
]
})
export default router
在Routes数组中定义路由对象
path属性表示路由的实际路径,name表示路由的名称,component表示路由对应的组件
导入组件的区别
import DomeView from '../views/DomeView.vue'
这种组件导入方式会使导入的组件全部加载
component:()=>import('../views/StuDangAn.vue') (异步加载)
这种导入组件的方式只有Vue用到这个组建的时候才会被加载
组件中路由的使用
<template>
<p>学生详情</p>
<p>{{$route.params.id}}</p>
<p>{{$route.params.name}}</p>
<p>{{$route.params.sex}}</p>
<p>
<router-link to="/stu/12345/nana/女/dangan">档案</router-link>|
<router-link to="/stu/12345/nana/女/chengji">成绩</router-link>
<router-view></router-view>
</p>
</template>
使用 <router-view></router-view> 来指定路由入口,也就是路由显示的组件的地方
<router-link to="/stu/12345/nana/女/chengji">成绩</router-link> 来指定路由链接
to 属性就表示最终去往的路由
路由的传值
path:'/stu/:id/:name/:sex',
name:'stu',
component:()=>import('../views/StuDView.vue')
在path属性中用:key 来定义路由传值
传值使用
<router-link to="/stu/12345/nana/女">详情</router-link>
对应上方的传值定义 id就为12345,name就为nana,sex就为女
嵌套路
在children中定义子路由 然后子路由不能path属性不能加斜杠
redirect属性表示第一次打开子路由是西东定向到那个路由
然后再用 <router-view></router-view> 和<router-link to="">档案</router-link>就能正常使用啦
{
path:'/stu/:id/:name/:sex',
name:'stu',
component:()=>import('../views/StuDView.vue'),
redirect:'stu/dangan',
children:[
{
//子路由不能加斜杠
path:'chengji',
component:()=>import("../views/StuChengJi.vue")
},
{
path:'dangan',
component:()=>import('../views/StuDangAn.vue')
}
]
}