vue-router 传递参数的几种方式
本文轉載自:https://blog.csdn.net/crazywoniu/article/details/80942642
vue-router傳遞參數分為兩大類
?
- 編程式的導航 router.push
- 聲明式的導航 <router-link>
編程式的導航 router.push
編程式導航傳遞參數有兩種類型:字符串、對象。字符串
字符串的方式是直接將路由地址以字符串的方式來跳轉,這種方式很簡單但是不能傳遞參數:this.$router.push("home");
對象
想要傳遞參數主要就是以對象的方式來寫,分為兩種方式:命名路由、查詢參數,下面分別說明兩種方式的用法和注意事項。命名路由
命名路由的前提就是在注冊路由的地方需要給路由命名如:命名路由傳遞參數需要使用params來傳遞,這里一定要注意使用params不是query。目標頁面接收傳遞參數時使用params
?特別注意:命名路由這種方式傳遞的參數,如果在目標頁面刷新是會出錯的
使用方法如下:
this.$router.push({ name: 'news', params: { userId: 123 }})代碼如下:
<template>
<div class="hello">
<h1>{{ msg }}</h1>
<button @click="routerTo">click here to news page</button>
</div>
</template>
<script>
export default {
name: 'HelloWorld',
data () {
? ? return {
msg: 'Welcome to Your Vue.js App'
}
},
?methods:{
routerTo(){
this.$router.push({ name: 'news', params: { userId: 123 }});
}
}
}
</script>
<style>
</style>
?
接受傳遞的參數:
<template><div>this is the news page.the transform param is {{this.$route.params.userId}}</div> </template> <script></script>?
運行效果如下:
?
查詢參數
查詢參數其實就是在路由地址后面帶上參數和傳統的url參數一致的,傳遞參數使用query而且必須配合path來傳遞參數而不能用name,目標頁面接收傳遞的參數使用query。注意:和name配對的是params,和path配對的是query
使用方法如下:
this.$router.push({ path: '/news', query: { userId: 123 }});
代碼如下:
<template><div class="hello"><h1>{{ msg }}</h1><button @click="routerTo">click here to news page</button></div></template><script>export default {name: 'HelloWorld',data () {return {msg: 'Welcome to Your Vue.js App'}},methods:{routerTo(){this.$router.push({ path: '/news', query: { userId: 123 }});}}}</script><style></style>?
接收參數如下:
<template><div>this is the news page.the transform param is {{this.$route.query.userId}}</div></template><script></script>?
運行效果如下:?
聲明式的導航
聲明式的導航和編程式的一樣,這里就不在過多介紹,給幾個例子大家對照編程式理解,例子如下:字符串
<router-link to="news">click to news page</router-link>命名路由
<router-link :to="{ name: 'news', params: { userId: 1111}}">click to news page</router-link> 運行效果如下:查詢參數
<router-link :to="{ path: '/news', query: { userId: 1111}}">click to news page</router-link> 運行效果如下:最后總結:路由傳遞參數和傳統傳遞參數是一樣的,命名路由類似表單提交而查詢就是url傳遞,在vue項目中基本上掌握了這兩種傳遞參數就能應付大部分應用了,最后總結為以下兩點:
1.命名路由搭配params,刷新頁面參數會丟失
2.查詢參數搭配query,刷新頁面數據不會丟失
3.接受參數使用this.$router后面就是搭配路由的名稱就能獲取到參數的值
?
?
?
?
?
轉載于:https://www.cnblogs.com/Sky-Ice/p/10443120.html
總結
以上是生活随笔為你收集整理的vue-router 传递参数的几种方式的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: jqgrid实现客户端导出Excel、t
- 下一篇: Ubuntu下apt-get命令详解(转