前端路由:URL中的hash(#号)与组件之间的对应关系。
1 Vue Router
- 介绍:Vue Router 是 Vue 官方路由。
- 组成:
- VueRouter:路由器类,根据路由请求在路由视图中动态渲染选中的组件
- <router-link>:请求链接组件,浏览器会解析为<a>
- <router-view>:动态视图组件,用来渲染展示与路由路径对应的组件
- 安装:(创建Vue项目时可选择)
- 定义路由表:记录 URL hash 与组件的对应关系。在src/router/index.js 中定义。有两种写法。参考下面案例。
案例:接上上个项目,通过VueRouter路由完成左侧菜单栏切换效果,
定义路由表有两种写法,这里只展示一种:注意需要去掉没有引用的import模块
src/router/index.js:
import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)
const routes = [
{
path: '/emp',
name: 'emp',
component: () => import('../views/EmpView.vue')
},
{
path: '/dept',
name: 'dept',
component: () => import('../views/DeptView.vue')
}
]
const router = new VueRouter({
routes
})
export default router
在main.js中,我们已经引入了router功能。
路由基本信息配置好了,路由表已经被加载,此时我们还缺少2个东西,就是<router-link>和<router-view>;,所以我们需要修改2个页面(EmpView.vue和DeptView.vue)我们左侧栏的2个按钮为router-link,其代码如下:
<el-menu-item index="1-1">
<router-link to="/dept">部门管理</router-link>
</el-menu-item>
<el-menu-item index="1-2">
<router-link to="/emp">员工管理</router-link>
</el-menu-item>
然后我们还需要在内容展示区域即App.vue中定义route-view,作为组件的切换,其App.vue的完整代码如下:
<template>
<div id="app">
<!-- {{message}} -->
<!-- <element-view></element-view> -->
<!-- <emp-view></emp-view> -->
<router-view></router-view>
</div>
</template>
<script>
// import EmpView './views/tlias/EmpView.vue'
// import ElementView './views/Element/ElementView.vue'
export default {
components: { },
data(){
return {
"message":"hello world"
}
}
}
</script>
<style>
</style>
但是我们浏览器打开地址: http://localhost:7000/ ,发现一片空白,因为我们默认的路由路径是/,但是路由配置中没有对应的关系,
所以我们需要在路由配置中/对应的路由组件,代码如下:
const routes = [
{
path: '/emp',
name: 'emp',
component: () => import('../views/tlias/EmpView.vue')
},
{
path: '/dept',
name: 'dept',
component: () => import('../views/tlias/DeptView.vue')
},
{
path: '/',
redirect:'/emp' //表示重定向到/emp即可
},
]
此时我们打开浏览器,访问http://localhost:7000 发现直接访问的是emp的页面,并且能够进行切换了,其具体如下图所示:
到此我们的路由实现成功。
test
test2