vue-router参数传递
生活随笔
收集整理的這篇文章主要介紹了
vue-router参数传递
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
vue-router參數傳遞
第一種:get方法
傳值:
<router-link :to="{path:'/get',query:{userId:123,username:'xia'}}">get跳轉</router-link> //或 <router-link :to="{name:'get',query:{userId:123,username:'xia'}}">get跳轉</router-link>接收值:
//在get.vue文件中 <template><div><p>get跳轉頁</p><p>userId:{{userId}}</p><p>username:{{username}}</p></div> </template> <script>export default {data(){return{//接收值:userId:this.$route.query.userId,username:this.$route.query.username,}}} </script>結果:url上顯示參數,頁面刷新后參數不會消失;
?
第二種:post方法
傳值:
<router-link :to="{name:'post',params:{stuId:456,stuName:'shang'}}">post跳轉</router-link> //路由path帶著路由參數params時,params不生效,錯誤示范: <router-link :to="{path:'/post',params:{stuId:456,stuName:'shang'}}">post跳轉</router-link>接收值:
<template><div><p>post頁面</p><p>studentId:{{stuId}}</p><p>studentName:{{stuName}}</p></div> </template> <script>export default {data(){return{//接收值:stuId:this.$route.params.stuId,stuName:this.$route.params.stuName,}}} </script>結果:url上不顯示參數,頁面刷新后參數會消失;
?
第三種:路由方法
傳值:
<router-link to="/route/789/zuo">路由跳轉</router-link>接收值:
<template><div><p>路由傳值</p><p>rouId:{{rouId}}</p><p>rouName:{{rouName}}</p></div> </template> <script>export default {data(){return{rouId:this.$route.params.rouId,rouName:this.$route.params.rouName,}}} </script>結果:url上顯示參數,頁面刷新后參數不會消失;
注意:
(1)
上文中router-link中的path和name都是路由里面的,頁面創建成功后一定要配置頁面的路由;
上文中第三種方法,還在路由中也進行了相應的配置;
路由中的配置:
import Vue from 'vue' import Router from 'vue-router' import HelloWorld from '@/components/HelloWorld'Vue.use(Router)export default new Router({routes: [{path: '/',name: 'HelloWorld',component: HelloWorld},{path: '/get',name:'get',component: resolve => require(['../components/get.vue'], resolve),meta: {title: 'get'},},{path: '/post',name:'post',component: resolve => require(['../components/post.vue'], resolve),meta: {title: 'post'},},{path: '/route/:rouId/:rouName?'name:'route',component: resolve => require(['../components/route.vue'], resolve),meta: {title: 'route'},}] })(2)
?當在鏈接上設置replace屬性,點擊時,會調用router.replace()而不是router.push(),于是瀏覽器不會留下history記錄,也就是無法返回上一頁,但會進入上上頁;
?(3)
在組件中獲取參數:
<template><div><p>{{$route.params.userId}}</p><p>{{$route.params.userName}}</p></div> </template>簡單說明router和route的區別:
$router :是指整個路由實例,你可以操控整個路由,用法如下:
- this.$router.go(-1); // 向前或者向后跳轉n個頁面,n可為正整數或負整數
- this.$router.push('/'); // 跳轉到指定url路徑,history棧中會有記錄,點擊返回會跳轉到上個頁面
- this.$router.replace('/'); // 跳轉到指定url路徑,但是history棧中不會有記錄,點擊返回會跳轉到上上個頁面
$route:是指當前路由實例$router跳轉到的路由對象;路由實例可以包含多個路由對象,它們是**父子包含關系**.
- this.$route.params.userId// 獲取路由傳遞過來的參數
- this.$route.query.userName// 獲取路由傳遞過來的參數
?
總結
以上是生活随笔為你收集整理的vue-router参数传递的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 5分钟了解vue-router的基本使用
- 下一篇: 路由组件传参