最近在學習Vue,本文介紹了vue params、query傳參使用,分享給大家,也給自己留個筆記
聲明式:<router-link :to="...">
編程式:router.push(...)
這兩種方式 都可以實現跳轉鏈接,在上篇文章繼續,通過A組件跳轉鏈接到B組件并且傳參數。
1、router.push使用
router/index.js
export default new Router({ routes: [ { path: '/', name: 'A', component: require('../components/A') }, { path: '/B/:name/:age', name: 'B', component: require('../components/B') } ]})上邊,在路由中為B組件添加兩個參數 name ,age
A組件,綁定一個@click事件,跳轉B組件傳參 使用params
<template> <div> <!---只允許有一個最外層標簽 !--> <div> <p>{{message}}</p> <p @click="toBFun">跳轉B組件啊啊</p> <!--<router-link :to="{ path: '/B',params:{name:'zs',age:22}}">跳轉B組件啊啊</router-link>--> </div> </div></template><script> export default { data: function () { return { message: 'vue好帥啊!' } }, methods: { toBFun: function(){ this.$router.push({name:'B',params:{name:'xy',age:22}}); } } }</script><style></style>這時瀏覽器會顯示 :http://localhost:8080/#/B/xy/22
在看下query 傳值及地址變化
同樣在 router/index.js路由文件中 不變有兩個參數name,age
{ path: '/B/:name/:age', name: 'B', component: require('../components/B') }在A組件中,之前參數傳遞是通過params,
this.$router.push({name:'B',params:{name:'xy',age:22}});替換后,query
this.$router.push({name:'B',query:{name:'xy',age:22}});這時瀏覽器會發現:http://localhost:8080/#/?name=xy&age=22
通過以上兩種,頁面刷新后,參數還會保留的。
獲取值有些不相同:
params:this.$route.params.name;
query:this.$route.query.name;
------------------------ 還有種方式--------------------------------------------
使用 router-link
<router-link :to="{ path: '/B',query:{name:'張飛',age:22}}">跳轉B組件</router-link>跳轉后,瀏覽器地址為:http://localhost:8080/#/B?name=zzz&age=22
跟 this.$router.push(...) 是一樣的
<router-link :to="{path:'/B/123'}"> 跳轉B組件</router-link> </div>{ path: '/B/:name', name: 'B', component: require('../components/B') }取值
this.$route.params.name
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。
新聞熱點
疑難解答