vue 路由传参方式

1、直接调用$router.push 实现携带参数的跳转通过params来传递参数

路由配置:写 /:id url上会直接显示参数值1,不写/:id url上不会显示

{
      path: '/learn',
      name: 'learn',
      component: Learn,
      children: [{
     	  path: '/page/:id',  //子路由配置
     	  name:'page',
          component: Page,
          }
      ]
    }

一级页面

<template>
  <div class="learn">
    <h3>{{ msg }}</h3>
    <h3>我是learn页</h3>
    <a @click="getData">路由传值</a> 
  //也可以写成<router-link to="/page/1">我是路由,点我跳转子页面</router-link> 直接携带参数 <router-view/> </div> </template> <script> export default { name: 'learn', data () { return { msg: '我是指定跳转的地址router页面', } }, methods:{ getData(){ //点击事件直接调用$router.push 实现携带参数的跳转 this.$router.push({ name: 'page', params: { id: "1" } }) } } } </script> <style scoped> h3 { font-weight: normal; color: #42b983; } </style>

接受传参的页面 

<template>
  <div class="page">
    <h3>{{ msg }}</h3>
    <h3>我是page页面</h3>
    <a @click="getData">点我看值</a>
    <p>{{$route.params.id}}</p>
  </div>
</template>

<script>
export default {
		  name: 'page',
		  data () {
		    return {
		      msg: '我是嵌入的子页面'
		    }
		  },
		  methods:{
		  	getData(){
		  		//可以用js获取,也可以直接用{{}}显示在页面上
		  		console.log(this.$route.params.id) //1
		  	
		  	}
		  	
		  
		  }
}
</script>

<style scoped>
 h3 {
  font-weight: normal;
  color: #42b983;
}

</style>

2、直接调用$router.push 实现携带参数的跳转通过query来传递参数 

 与第一种params传值类似,但写不写 /:id url上都会显示?id=1

getData(){
	//点击事件直接调用$router.push 实现携带参数的跳转
	this.$router.push({
	 name: 'page',
		 query: {
			 id: "1"
	      }
	})
			
}

接收

<p>{{$route.query.id}}</p>
getData(){
	 //可以用js获取,也可以直接用{{}}显示在页面上
	 console.log(this.$route.query.id) //1
		  	
	}

 3、通过router-link中的to属性

<router-link :to="{name:'page',params:{id:'1'}}">路由传参</router-link>

  

  

原文地址:https://www.cnblogs.com/xiaobaibubai/p/12213872.html