vue-router傳參的四種方式超詳細講解
vue路由傳參的四種方式
一、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
調用方法:
<router-link to="/father/son/傳入的參數(shù)">父親組件<router-link> 子組件通過 this.$route.params.num 接受參數(shù)
二、調用$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>傳入參數(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>
工作中經常用的也就是上面的幾種傳參方式,完結~ 歡迎點贊收藏哦
補充知識:
vue-router傳遞參數(shù)的幾種方式
vue-router傳遞參數(shù)分為兩大類
1 編程式的導航 router.push
2聲明式的導航
編程式的導航 router.push
編程式導航傳遞參數(shù)有兩種類型:字符串、對象。
字符串
字符串的方式是直接將路由地址以字符串的方式來跳轉,這種方式很簡單但是不能傳遞參數(shù):
this.$router.push("home");
對象
使用方法如下:
this.$router.push({ name: 'news', params: { userId: 123 }})
name:為路由的名字
獲取參數(shù)
{{this.$route.params.userId}}
查詢參數(shù)
使用方法如下:
this.$router.push({ path: '/news', query: { userId: 123 }});
獲取參數(shù)
{{this.$route.query.userId}}
聲明式的導航
字符串方式
click to news page
命名路由方式
click to news page
查詢參數(shù)方式
click to news page
1.命名路由搭配params,刷新頁面參數(shù)會丟失
2.查詢參數(shù)搭配query,刷新頁面數(shù)據(jù)不會丟失
3.接受參數(shù)使用this.$router后面就是搭配路由的名稱就能獲取到參數(shù)的值
到此這篇關于vue-router傳參的四種方式超詳細的文章就介紹到這了,更多相關vue-router傳參方式內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
vue事件監(jiān)聽函數(shù)on中的this指針域使用
這篇文章主要介紹了vue事件監(jiān)聽函數(shù)on中的this指針域使用方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-08-08