若依路由机制
一、
vue项目的界面在public下的index.html里呈现。main.js是程序的入口,定义vue实例对象。
new Vue({
el: '#app',
router,//路由插件
store,//vuex插件,所有的组件中都可以使用store中的action,mutation和state数据。通过$strore调用或者mapXXX函数映射
render: h => h(App)
})
el是配置vm实例要填充的public/index.html里的元素对象。render属性配置的是用App.vue组件进行填充。在vm实例对象挂载完成之前,即mouted函数执行之前,页面显示的是index.html中本身的元素,在挂载完成后,会显示App.vue中的元素。
App.vue
<template>
<div id="app">
<router-view/>
</div>
</template>
<div id="app">
: 是一个HTMLdiv
元素,其id
属性为app
。在Vue应用中,这个div
通常是整个应用的根元素,Vue实例会挂载在这个元素上。<router-view />
: 是Vue Router的一个组件,代表路由视图占位符。Vue Router根据当前URL匹配相应的组件,并将其渲染在此处。换句话说,这是路由内容显示的地方。
通过使用Vue Router,可以根据不同的URL路径,在<router-view />
位置动态加载和显示不同的组件或页面内容。
二、路由配置
路由的配置在router/index.js下:
{
path: '',
component: Layout,
redirect: 'index',
children: [
{
path: 'index',
component: () => import('@/views/index'),
name: 'Index',
meta: { title: '首页', icon: 'dashboard', affix: true }
}
]
}
-
component: Layout
。表示使用框架的布局容器(通常包含侧边栏、导航栏等公共组件)子路由的内容会渲染在Layout
组件中的<router-view>
位置 -
父路由路径
''
+ 子路由路径'index'
= 实际访问路径 /index -
component: () => import('@/views/index') // 路由懒加载
,使用动态导入实现代码分割,优化首屏加载速度只有当访问该路由时才会加载对应组件
Layout组件
动态路由,关键代码在sidebar文件中
<sidebar-item
v-for="(route, index) in permission_routes"
:key="route.path + index"
:item="route"
:base-path="route.path"
:first="true"/>
<script>
import {mapGetters, mapState} from 'vuex'
export default {
computed: {
...mapGetters(['permission_routes', 'sidebar']),
}
}
</script>
从vuex获取到路由,其具体实现在store/modules/permission.js中。
const permission = {
state: {
routes: [],
addRoutes: []
},
mutations: {
SET_ROUTES: (state, routes) => {
state.addRoutes = routes
state.routes = constantRoutes.concat(routes)
}
},
actions: {
// 生成路由
GenerateRoutes({ commit }) {
return new Promise(resolve => {
// 向后端请求路由数据
getRouters().then(res => {
const accessedRoutes = filterAsyncRouter(res.data)
accessedRoutes.push({ path: '*', redirect: '/404', hidden: true })
commit('SET_ROUTES', accessedRoutes)
resolve(accessedRoutes)
})
})
}
}
}
// 遍历后台传来的路由字符串,转换为组件对象
function filterAsyncRouter(asyncRouterMap) {
return asyncRouterMap.filter(route => {
if (route.component) {
// Layout组件特殊处理
if (route.component === 'Layout') {
route.component = Layout
} else {
route.component = loadView(route.component)
}
}
if (route.children != null && route.children && route.children.length) {
route.children = filterAsyncRouter(route.children)
}
return true
})
}
export const loadView = (view) => { // 路由懒加载
return (resolve) => require([`@/views/${view}`], resolve)
}
export default permission