e:\vue\myproject
components下新建/news文件夾用于本章測(cè)試
路由傳參
https://segmentfault.com/a/1190000018711422?utm_source=tag-newest
- 動(dòng)態(tài)路由傳參
- params傳參
- query傳參
1未桥、動(dòng)態(tài)路由匹配restful
動(dòng)態(tài)路由傳參,類似restful,在請(qǐng)求url里帶參數(shù)
官網(wǎng)示例:
https://jsfiddle.net/yyx990803/4xfa2f19/
1、news/index.vue
<template>
<div>
<p>新聞頁(yè)</p>
<ul>
<li><router-link to="/newslist/123">美國(guó)新冠肺炎確診病例升至50206例 死亡606例</router-link></li>
<li><router-link to="/newslist/124">意大利新增確診病例5249例 累計(jì)69176例</router-link></li>
</ul>
<router-view/>
</div>
</template>
<script>
</script>
<style>
ul{
list-style: none;
}
</style>
2蚀乔、創(chuàng)建路由組件news.vue
<template>
<h1>這是新聞{{ $route.params.userId }}</h1>
</template>
<script>
export default {
data() {
return {
};
}
}
</script>
2崔步、定義路由
import newsindex from '@/components/news/index'
import newslist from '@/components/news/newslist'
{
path: '/news',
name: 'news',
component: newsindex
},
{
path: '/newslist/:userId',
name: 'newslist',
component: newslist
}
測(cè)試一下
可以將參數(shù)攜帶過(guò)去源梭,后續(xù)可以根據(jù)id查詢?cè)亠@示新聞詳情
2、路由命名和編程式的導(dǎo)航
這種方式需要為路由命名,然后再通過(guò)編程實(shí)現(xiàn)跳轉(zhuǎn)
官網(wǎng)api:
命名路由:https://router.vuejs.org/zh/guide/essentials/named-routes.html
編程式的導(dǎo)航:https://router.vuejs.org/zh/guide/essentials/navigation.html
有兩種方式
2.1通過(guò)params來(lái)傳遞參數(shù)##
** {name: , params} **
相當(dāng)于路徑參數(shù)/home/:id
step 1 :編寫newslist2.vue
<template>
<div>
<h1>這是params新聞:{{ $route.params.id }}</h1>
<h1>這是query新聞:{{ $route.query.id }}</h1>
</div>
</template>
<script>
export default{
data(){
return {}
}
}
</script>
step1 路由配置中必須有name屬性 (如name: 'newslist2')
{
path: '/newslist2',
name: 'newslist2',
component: newslist2
}
step2 news/index.vue中增加鏈接
<li><router-link :to="{name:'newslist2',params:{id:45678}}">新聞params傳參</router-link></li>
測(cè)試:
http://localhost:8080/#/news
** 注意稍味,編程時(shí)也可以通過(guò)事件觸發(fā) **
<router-link :to="{name:'home',params:{id:45678}}">跟代碼調(diào)用 router.push() 是一回事:
router.push({ name: 'user', params: { id: 123 }})
2.2 通過(guò)query傳參數(shù)
** name/query 或者 path/query **
相當(dāng)于get請(qǐng)求方式咸产,在url后面追加參數(shù)?userId=?&userName=......
關(guān)鍵代碼
<router-link :to="{path:'newslist2',query:{id:8907777}}">query2</router-link>
頁(yè)面部分:
<h1>這是query新聞:{{ $route.query.id }}</h1>
總結(jié)params與query異同
https://blog.csdn.net/unbreakablec/article/details/87159511