1. 程式人生 > 其它 >Vue中this.$router.push(引數) 實現頁面跳轉

Vue中this.$router.push(引數) 實現頁面跳轉

很多情況下,我們在執行點選按鈕跳轉頁面之前還會執行一系列方法,這時可以使用 this.$router.push(location) 來修改 url,完成跳轉。

push 後面可以是物件,也可以是字串:

// 字串
this.$router.push('/home/first')
// 物件 query相當與傳送了一次get請求,請求引數會顯示在瀏覽器位址列中
this.$router.push({ path: '/home/first' })
// 命名的路由 params相當與傳送了一次post請求,請求引數則不會顯示,並且重新整理頁面之後引數會消失
this.$router.push({ name:'Login', params: { id: this.id } )

// 當路由配置更改為
//路由配置:

//{path:'/login/:id',name:'Login',component:Login}

//並且再次傳送請求,請求資料不會隨著頁面的重新整理而消失
跳轉頁面並傳遞引數的方法:

1.Params

由於動態路由也是傳遞params的,所以在 this.$router.push() 方法中path不能和params一起使用,否則params將無效。需要用name來指定頁面。

及通過路由配置的name屬性訪問

在路由配置檔案中定義引數:

/* router.js 檔案*/
import Vue from "vue";
import Router from "vue-router";
import MediaSecond from "@/views/EnterprisePage/MediaMatrix/second"; //資訊列表

Vue.use(Router);
export default new Router({
routes: [ /* 進行路由配置 */
{
name: "MediaSecond",
path: "/MediaSecond",
component: MediaSecond
},
]
})

/* 後面還需要接一空行,否則無法通過 ESlint 語法驗證 */
通過name獲取頁面,傳遞params:

this.$router.push({ name: 'MediaSecond',params:{artistName:artistName,imgUrl:imgUrl,type:2} })
在目標頁面通過this.$route.params獲取引數:

if (this.$route.params.type == 2) {
this.type = apis.getAtistDetails;
} else {
this.type = apis.getMessageList;
}
2.Query

頁面通過path/name和query傳遞引數,該例項中row為某行表格資料

this.$router.push({ name: 'DetailManagement', query: { auditID: row.id, type: '2' } });
this.$router.push({ path: '/DetailManagement', query: { auditID: row.id, type: '2' } });
在目標頁面通過this.$route.query獲取引數:

this.$route.query.type