1、router-link 方式【实现跳转最简单的方法】
<router-link to='需要跳转到的页面的路径>
如:
<div id="index"> <router-link to="/home">首页</router-link> <router-link :to="{name: 'home'}">首页</router-link> </div> <router-view/>
<!--<router-link> 就是定义页面中点击的部分,<router-view> 定义显示部分,就是点击后,区配的内容显示在什么地方,会被匹配到的组件替换掉-->
路由配置:
import Vue from 'vue' import Router from 'vue-router' import Home from '@/components/Home.vue' Vue.use(Router) export default new Router({ //vue-router中默认使用的是hash模式,URL中带有#号 //我们可以用如下代码修改成history模式: mode:'history', routes: [ { path: '/home', component: Home }, //默认跳转路由 { path: '/',//或者* component: Home } ] })
2、路由带参数跳转
如下代码:
<button @click="goHome()">首页</button> goHome(){ var id =‘123’ this.$router.push({path:'/home',query:{id}}) this.$router.push({name:'home',params:{id}}) //等价于: this.$router.push({path:'/home',query:{id:'123'}}) this.$router.push({name:'home',params:{id:'123'}}) }
多个参数:
this.$router.push({name:'home',params:{id:'123',title: 'title2'}})
获取路由参数:
this.$route.query ;
this.$route.params;
3.this.$router.go(n) 向前或者向后跳转n个页面,n可为正整数或负整数
**区别**
this.$router.push 跳转到指定url路径,并想history栈中添加一个记录,点击后退会返回到上一个页面
this.$router.replace 跳转到指定url路径,但是history栈中不会有记录,点击返回会跳转到上上个页面 (就是直接替换了当前页面)
this.$router.go(n) 向前或者向后跳转n个页面,n可为正整数或负整数