在頁面中可以通過以下方式使用路由
1:通過router-link標籤的方式
<router-link to="home">Home</router-link>
2:通過router的push的方式
this.$router.push({path: ‘/manage’});
在執行點擊按鈕跳轉頁面之前還會執行一系列方法,這時可以使用 this.$router.push(location) 來修改 url,完成跳轉。
push 後面可以是對象,也可以是字符串:
// 字符串
this.$router.push('/home/first')
// 對象
this.$router.push({ path: '/home/first' })
// 命名的路由
this.$router.push({ name: 'home', params: { userId: wise }})
通過代碼跳轉案例
<template>
<div>
<button @click='userClick'>用戶</button>
<button @click='profileClick'>檔案</button>
</div>
</template>
<script>
export default{
data(){
return {
userId:'wushen'
}
},
methods:{
userClick(){
this.$route.push('/user/'+this.userId)
},
profileClick(){
this.$route.push({
path: '/profile',
query: {
name: 'wushen',
age:18,
height:1.88
}
})
}
}
}
</script>
跳轉頁面並傳遞參數的方法:
1.Params
-
this.$router.push({name:"",params:{id:""}})
name和params搭配刷新參數會消失 -
this.$router.push({path:"",query:{id:""}})
path和query搭配,刷新頁面參數不會消失,query中參數成了url中的一部分
由於動態路由也是傳遞params的,所以在 this.$router.push() 方法中path不能和params一起使用,否則params將無效。需要用name來指定頁面。
及通過路由配置的name屬性訪問
兩種方式的區別是query傳參的參數會帶在url後邊展示在地址欄,params傳參的參數不會展示到地址欄。
在路由配置文件中定義參數:
/* 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
1.需要注意的是接收參數的時候是route而不是router。兩種方式一一對應,名字不能混用。
2.由於動態路由也是傳遞params的,所以在 this.$router.push() 方法中path不能和params一起使用,否則params將無效。只能用name來指定頁面。
3.不帶參數,直接跳轉頁面
this.$router.push('/orderList')
this.$router.push({name:'orderList'})
this.$router.push({path:'/orderList'})
用query傳參對象時需注意的地方
在vue項目中,我們用函數式編程this.$router.push跳轉,用query傳遞一個對象時要把這個對象先轉化爲字符串,然後在接收的時候要轉化爲對象,要不然會接收不到參數。要不就把參數分開傳遞,不要放到對象裏。
this.$router.push({
path: '/liveing',
query: {
routeParams: JSON.stringify({ liveUrl: url, flag: 2 })
}
});
接收:
let routeParams = JSON.parse(this.$route.query.routeParams)
this.currMeetingUrl = routeParams.liveUrl;
this.obcject = routeParams.flag;
第二種方法:不要套在對象裏直接傳遞
this.$router.push({
path: '/liveing',
query: {
liveUrl: url,
flag: 2
}
});
接收:
let liveUrl = this.$route.query.liveUrl;
let flag = this.$route.query.flag;