vue3第五课:定义路由及模块
分不太清vue里面的模块及模板的概念。姑且就这么叫吧。这里是照着知乎登录及首页来布局的。
1 分析及创建模块
具体可以参考知乎登录页和首页
这里进行了模块划分
在src目录下建立相应的views模块
2 配置路由
路由的路径/src/router/index.js
代码如下:
// router/index.js
import { createRouter, createWebHistory } from 'vue-router'
import index from '../views/index/index.vue'
import login from '../views/login/login.vue'
import school from '../views/school/index.vue'
import find from '../views/find/index.vue'
import waiting from '../views/waiting/index.vue'
import follow from '../views/index/follow/index.vue'
import recommend from '../views/index/recommend/index.vue'
import video from '../views/index/video/index.vue'
import hotlist from '../views/index/hotlist/index.vue'
const routes = [
{ path: '/', component: index },
{ path: '/login', component: login },
{
path: '/index',
component: index,
children:[
{ path: 'follow', component: follow },
{ path: 'hotlist', component: hotlist },
{ path: 'video', component: video },
{ path: 'recommend', component: recommend },
]
},
{ path: '/school', component: school },
{ path: '/find', component: find },
{ path: '/waiting', component: waiting },
]
const router = createRouter({
history: createWebHistory(),
routes,
})
export default router
需要注意的是子路由的配置。
3 路由的引用
要确保路由已经引用。
打开main.js,代码如下:
import { createApp } from 'vue'
import './style.css'
import App from './App.vue'
import router from "./router"
createApp(App).use(router).mount('#app')
4 组件的渲染
在Vue 组件中,使用<router-link>
来导航到你的路由,并使用<router-view>
来显示当前路由的组件。
根组件就是App.vue,所以先把App.vue里的东西清一下。并加入<router-view></router-view>
标签
App.vue代码如下
<script setup>
</script>
<template>
<router-view></router-view>
</template>
<style scoped>
</style>
5 子路由组件的渲染
正如上条,子路由组件的渲染,需要上一层级组件中包含<router-view></router-view>
来确定渲染的位置。
首页/index 下有关注/热门/推荐/视频四个子组件,那么需要在views/index/index.vue中加入<router-view></router-view>
<template>
<div>index</div>
<router-view></router-view>
</template>
这样在访问地址/index/follow后,就能将views/index/follow/index.vue中的内容渲染出来。
你也看到了,真JB烦人。以前搞jquery+bootstrap是多么容易理解。也不知道是进步还是退步。
评论已关闭