# 布局
# 布局
布局代码在 src/layout 里。
Vue 前端项目大部分页面都基于这个 layout,除了个别页面例如:login,404,401 等页面。如果想在一个项目中有多种不同的 layout,只要在一级路由选择不同的 layout 组件就行。
// No layout
{
path: '/401',
component: () => import('errorPage/401')
}
// Has layout
{
path: '/documentation',
// 你可以选择不同的 layout 组件
component: Layout,
// 这里开始对应的路由都会显示在内容区域中
children: [{
path: 'index',
component: () => import('documentation/index'),
name: 'documentation'
}]
}
# 内容区域
内容区域代码在 src/layout/components/AppMain.vue。
在内容区域外部包了一层 keep-alive 主要为了缓存 ,配合页面的 tabs-view 标签导航使用,若不需要可自行去除。
其中 transition 定义页面之间切换动画,可以根据需求自行修改转场动画。默认提供 fade 和 fade-transform 两个转场动画,具体 css 实现见 src/styles/transition.scss。如果需要调整可在 AppMain.vue 中调整 transition 的 name。
# router-view
路由不同但 Vue 组件相同在真实的业务场景中很多,例如:
{ path: 'create', component: PostCreate, name: '创建文章' },
{ path: 'edit/:id(\\d+)', component: PostCreate, name: '编辑文章' }
创建和编辑的页面使用的是同一个 component,默认情况下这两个页面切换时不会触发 Vue 的 created 或者 mounted 钩子,Vue 官方说可以通过 watch $route 的变化进行处理。但更简单的方法是在 router-view 加上一个唯一的 key,保证路由切换时都会重新渲染触发钩子。
<router-view :key="key"></router-view>
computed: {
key() {
// 只要保证 key 唯一性就可以了,保证不同页面的 key 不相同
return this.$route.fullPath
}
}
也可以像 src/views/example 中 editForm 和 createForm 声明两个不同的 view 但引入同一个 component。
<!-- create.vue -->
<template>
<article-detail :is-edit='false'></article-detail> //create
</template>
<script>
import ArticleDetail from './components/ArticleDetail'
</script>
<!-- edit.vue -->
<template>
<article-detail :is-edit='true'></article-detail> //edit
</template>
<script>
import ArticleDetail from './components/ArticleDetail'
</script>