1. 安装vue-router库
将vue-router库安装到项目中,执行命令:
npm install vue-router -S
2. 配置路由映射
在src/router目录下,创建一个index.js路由映射文件,内容如下:
import Vue from 'vue'
import VueRouter from 'vue-router'
// 安装路由插件
Vue.use(VueRouter)
// 路由映射表
const routes = [
{
path: '/', // 默认加载首页相关的组件
component: () => import('@/components/HelloWorld'),
},
{
path: '/home',
redirect: '/' // 重定向到首页
},
{
path: '/user/page1',
name: 'page1',
component: () => import('@/views/test/page1'),
}
]
const router = new VueRouter({
// 使用HTML5的history模式,该模式下可以去除路径中的#号
mode: 'history',
routes: routes
})
// 重写路由的push方法,解决多次调用同一个push方法出现的问题
const routerPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
return routerPush.call(this, location).catch(error=> error)
}
export default router
参数说明:
path:路由路径,随意定义,可以为多级,此处信息将会出现在浏览器地址栏中,位于#号后面。
name:路由名称,pramas传参时使用的就是这里定义的名称。
component:组件,每个路由,必须要有一个组件。
3. 引入路由映射文件
在main.js文件中,引入index.js路由映射文件,如下:
import router from '@/router/index'
如图:
4. 路由装载
在app.vue文件中,定义router-view标签,用来装载路由对应的组件内容,如下:
<router-view></router-view>
注意:这一步非常重要,缺少router-view标签,路由将无法渲染和跳转。
5. 同一个页面装载多个组件
index.js路由映射文件中,定义多个组件,如下:
页面中,使用router-view标签进行调用,如下:
6. 路由跳转
6.1 router-link标签跳转
【通过路由映射表中的path属性进行跳转】
<!-- 直接跳转(推荐) -->
<router-link to='/user/page1'>
<el-button type="success">点击跳转1</el-button>
</router-link>
<!-- query带参数跳转(推荐) -->
<router-link :to="{path:'/user/page1',query:{id:123}}">
<el-button type="info">点击跳转2</el-button>
</router-link>
【通过路由映射表中的name属性进行跳转】
<!-- 直接跳转(不推荐) -->
<router-link :to="{name:'page1'}">
<el-button type="warning">点击跳转3</el-button>
</router-link>
<!-- params带参数跳转(推荐)-->
<router-link :to="{name:'page1',params:{id:125}}">
<el-button type="danger">点击跳转4</el-button>
</router-link>
注意:router-link标签是vue-router的内置组件,最终它会被渲染成一个<a>标签。
6.2 this.$router.push()跳转
<button @click='goTo()'>点击跳转</button>
methods: {
goTo: function () {
// 直接跳转
this.$router.push('/user/page1');
// 带参数跳转
this.$router.push({path:'/user/page1',query:{id:123}});
this.$router.push({name:'page1',params:{id:123}});
}
}
6.3 获取参数
获取query参数:this.$route.query
获取params参数:this.$route.params
获取后的结果,均为一个对象。
注意:
1. query方式的传参相当于get请求,而params方式的传参相当于post请求。
2. params方式的传参,在路由相同,参数不同的情况下,会导致页面无法刷新。
3. 页面中获取参数的方式:
{{this.$route.query.参数名称}}或者{{this.$route.params.参数名称}}