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可為正整數或負整數