项目背景:vue2
业务需求:用Vue+Element 写一个前端框架
今日主线任务:简单地从登陆页跳转到首页
项目地址:https://gitee.com/whwbs/my_project.githttps://gitee.com/whwbs/my_project.git
准备工作:vue-router (^3.1.3)
新建三个文件
my_project/src/router/routes.js
my_project/src/router/index.js
my_project/src/views/system/index/index.vue // 首页文件
main.js文件中导入routes.js
import router from './router'
new Vue({
router,
render: h => h(App),
}).$mount('#app')
routes.js中声明
// 由于懒加载页面太多的话会造成webpack热更新太慢,所以开发环境不使用懒加载,只有生产环境使用懒加载
const _import = require('@/libs/util.import.' + process.env.NODE_ENV)
const routes = [
{
path: '/',
redirect: { name: 'login' },
component: _import('system/login'),
children: [
// 登陆
{
path: 'login',
name: 'login',
meta: {
title: '登陆',
},
component: _import('system/login')
},
]
},
{
path: '/index',
name: 'index',
meta: {
title: '首页',
},
component: _import('system/index')
},
]
// 重新组织后导出
export default [
...routes,
]
这里单纯的为了项目结构好看,将登录页改到my_project/src/views/system/login件夹下,记得挪。
my_project/src/libs/util.import.development.js
module.exports = file => require('@/views/' + file).default
my_project/src/router/index.js
import Vue from 'vue'
import VueRouter from 'vue-router'
// 路由数据
import routes from './routes'
// fix vue-router NavigationDuplicated
const VueRouterPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location) {
return VueRouterPush.call(this, location).catch(err => err)
}
const VueRouterReplace = VueRouter.prototype.replace
VueRouter.prototype.replace = function replace (location) {
return VueRouterReplace.call(this, location).catch(err => err)
}
Vue.use(VueRouter)
// 导出路由 在 main.js 里使用
const router = new VueRouter({
routes
})
export default router
main.js router/index.js router/routes.js之间的引用关系是
router/routes.js--> router/index.js(vue-router) --> main.js
my_project/src/views/system/login/index.vue submit方法中加入路由跳转
this.$router.push({ path: '/index' });
改造下my_project/src/App.vue代码
<template>
<div id="app">
<!-- 登陆页 -->
<router-view />
</div>
</template>
router-view组件作为vue最核心的路由管理组件,在项目中作为路由管理经常被使用到,另外,vue-router在本文算是牛刀小试,后期会较深入使用,需要好好了解。
做完以上,在system/index/index.vue 随便写点,点击登录看看效果。