vue基础——java程序员版(vue路由)
1、引入路由
在控制台执行vue ui,在插件市场里可以找到vue-router并导入。
一般情况下,vue会自动在main,js中引入vue-router,如下:
import Vue from 'vue'
import App from './App.vue'
import './plugins/element.js'
import router from './router'
Vue.config.productionTip = false
new Vue({router,render: h => h(App)
}).$mount('#app')
2、路由跳转的页面构成
这是vue自动生成的主页面(app.vue),对于router-link
标签可以理解为a标签点击可以进行视图跳转,对于router-view
标签就是展示视图的地方,通过点击不同的router-link,router-view展示对应路由的组件。
<template><div id="app"><nav><router-link to="/">Home</router-link> |<router-link to="/about">About</router-link> |</nav>
<!-- 占位符展示视图的位置,点击上面的router-link,在这里展示不同的页面--><router-view/></div>
</template>
3、配置路由
路由的配置文件位于src/router/index.js
,修改index.js来配置路由。下面有两种配置路由的方式:动态和静态,推荐使用动态引入,对于parh="*"
的路径表示访问路由不存在所访问的组件,当然这里是从定向到自定义的404组件了。
import Vue from 'vue'
import VueRouter from 'vue-router'
import HomeView from '../views/HomeView.vue'Vue.use(VueRouter)
// 路由表
const 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(/* webpackChunkName: "about" */ '../views/AboutView.vue')},//404{path: '/404',component: ()=>import('../components/404.vue')},// 假如请求的路由上面都没有,就会跳转到这个路由{path: '*',// 重定向到404redirect: '/404'}
]
const router = new VueRouter({routes
})export default router
4、路由嵌套
对应一个组件它当然也可以想app.vue一样使用路由,只需要配置它的子路由即可,在children: [ ]中配置子路由规则和正常路由一样。此时访问/c/p1就是P1View组件替换 ContainerView的< router-view/>
//嵌套路由{path: '/c',component: () => import('../views/element/ContainerView.vue'),// 默认访问/c重定向到/c/p1redirect: '/c/p1' ,// 子路由,对应路由展示到父路由的组件内部,也就是切换的是ContainerView.vue的<router-view/>children: [{path: '/c/p1',component: () => import('../views/element/P1View.vue'),},{path: '/c/p2',component: () => import('../views/element/P2View.vue'),},{path: '/c/p3',component: () => import('../views/element/P3View.vue'),}]},
ContainerView.vue使用了element-ui的布局容器
<template>
<div><el-container><el-header>Header</el-header><el-container><el-aside width="200px"><router-link to="/c/p1">p1</router-link><br><router-link to="/c/p2">p2</router-link><br><router-link to="/c/p3">p3</router-link><br></el-aside><el-main><router-view/></el-main></el-container></el-container>
</div>
</template>
<style>
.el-header, .el-footer {background-color: #B3C0D1;color: #333;text-align: center;line-height: 60px;
}.el-aside {background-color: #D3DCE6;color: #333;text-align: center;line-height: 200px;
}.el-main {background-color: #E9EEF3;color: #333;text-align: center;line-height: 160px;
}body > .el-container {margin-bottom: 40px;
}.el-container:nth-child(5) .el-aside,
.el-container:nth-child(6) .el-aside {line-height: 260px;
}.el-container:nth-child(7) .el-aside {line-height: 320px;
}
</style>