傳參:
1. 頁面式(html)標簽路由跳轉傳參 ----- router-link(其實就是a標簽)
2. js編程式路由跳轉 ----- this.$router.push() // params query
3. 路由組件傳參 ----- 在路由配置中用分號拼接參數
獲取參數:
1. this.$router.params ----- 搭配路由的name屬性,參數作為路由的一部分,不會在url顯示
2. this.$router.query ----- 使用path來匹配路由,可以在url看到?后面的就是傳遞的參數
一、router-link
<router-link :to="{path:'/news/detail',query:{id:1}}">詳情</router-link>
使用path + 路徑,query + 參數。則用this.$route.query.id取值。
<router-link :to="{name:'newsDetail',params:{id:1}}">詳情</router-link>
使用name +路由名稱,params + 參數。則用this.$route.params.id取值。
二、this.$router.push() ----- key,value鍵值對的形式
1. query 顯示在url
// 傳參
sendData(){ this.$router.push({ path: './describe', query: { id:id, title:title } }) }
// 接收參數 this.$route.query.id this.$route.query.title
2. params 不會顯示在url
// 傳參 sendData(){ this.$router.push({ name: './describe', params: { id:id, title:title } }) }
// 接收參數 this.$route.params.id this.$route.params.title
三、路由組件傳參
路由部分:
let routes = [ { path: '/news', name: 'news', props: true, meta: {}, component: () => import('@/page/news.vue') },{ path: '/newsDetail/:id', name: 'newsDetail', props: true, meta: {}, component: () => import('@/page/newsDetail.vue') } ]
path后面跟占位符,props設置為波爾類型,true。跳轉頁面時使用this.$router.push傳參。
下面是取值的方式
export default { name: 'HelloWorld', data () { return { msg: '123 } }, props:['id'], mounted(){ console.log(this.$route.params.id, this.id) } }
取值時,方法1:可以直接使用this.$route.params.id取值。
方法2:也可以先放到props中,就可以直接用this.id拿到了。
參考:https://www.cnblogs.com/freedom-feng/p/11528836.html
