vue-router傳參的4種方式超詳細講解
一、router-link路由導航方式傳參
父組件:<router-link to="/跳轉到的路徑/傳入的參數(shù)"></router-link>
子組件:this.$route.params.content接受父組件傳遞過來的參數(shù)
例如:
路由配置:
bashbash{path:'/father/son/:num',name:A,component:A}```
地址欄中的顯示:
http://localhost:8080/#/father/son/44
調(diào)用方法:
<router-link to="/father/son/傳入的參數(shù)">父親組件<router-link> 子組件通過 this.$route.params.num 接受參數(shù)
二、調(diào)用$router.push實現(xiàn)路由傳參
父組件:通過實踐觸發(fā),跳轉代碼
<button @click="clickHand(123)">push傳參</button>
methods: {
clickHand(id) {
this.$router.push({
path: `/d/${id}`
})
}
}
路由配置
{path: '/d/:id', name: D, component: D}
地址欄中顯示:
http://localhost:8080/d/123
子組件接受參數(shù)方式
mounted () {
this.id = this.$route.params.id
}
三、通過路由屬性name匹配路由,再根據(jù)params傳遞參數(shù)
父組件:
<button @click="ClickByName()">params傳參</button>
ClickByName() {
this.$router.push({
name: 'B',
params: {
context: '吳又可吳又可吳又可'
}
})
}
路由配置:路徑后不需要在加上傳入的參數(shù),但是name必須和父組件中的name一致
{path: '/b', name: 'B', component: B}
地址欄中的顯示:地址欄不會帶有傳入的參數(shù),而且再次刷新頁面后參數(shù)會丟失
http://localhost:8080/#/b
子組件接收參數(shù)的方式:
<template>
<div id="b">
This is page B!
<p>傳入?yún)?shù):{{this.$route.params.context}}</p>
</div>
</template>
四、通過query來傳遞參數(shù)
父組件:
<button @click="clickQuery()">query傳參</button>
clickQuery() {
this.$router.push({
path: '/c',
query: {
context: '吳又可吳又可'
}
})
}路由配置:不需要做任何修改
{path: '/c', name: 'C', component: C}
地址欄中的顯示(中文轉碼格式):
http://localhost:8080/#/c?sometext=%E8%BF%99%E6%98%AF%E5%B0%8F%E7%BE%8A%E5%90%8C%E5%AD%A6
子組件接受方法:
<template>
<div id="C">
This is page C!
<p>這是父組件傳入的數(shù)據(jù): {{this.$route.query.context}}</p>
</div>
</template>
工作中經(jīng)常用的也就是上面的幾種傳參方式,完結~
總結
到此這篇關于vue-router傳參的4種方式的文章就介紹到這了,更多相關vue-router傳參方式內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Vue實現(xiàn)用戶自定義字段顯示數(shù)據(jù)的方法
今天小編就為大家分享一篇Vue實現(xiàn)用戶自定義字段顯示數(shù)據(jù)的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-08-08
Vue+FormData+axios實現(xiàn)圖片上傳功能
這篇文章主要為大家學習介紹了Vue如何利用FormData和axios實現(xiàn)圖片上傳功能,本文為大家整理了詳細步驟,感興趣的小伙伴可以了解一下2023-08-08
vue3.0語法糖內(nèi)的defineProps及defineEmits解析
這篇文章主要介紹了vue3.0語法糖內(nèi)的defineProps及defineEmits解析,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-04-04

