vue-router路由传参方式

vue路由传参方式

一、router-link路由导航方式传参

父组件:<router-link to="/跳转到的路径/传入的参数"></router-link>
子组件:this.$route.params.content 接受父组件传递过来的参数

例如:
路由配置:

bashbash{
    
    path:'/father/son/:num',name:A,component:A}

地址栏中的显示:
http://localhost:8080/#/father/son/44

调用方法:

<router-link to="/father/son/传入的参数">父亲组件<router-link>
子组件通过  this.$route.params.num 接受参数

二、调用$router.push实现路由传参

父组件:通过实践触发,跳转代码:

<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

子组件接受参数方式:

mounted () {
    
    
	this.id = this.$route.params.id
}

三、通过路由属性name匹配路由,再根据params传递参数

父组件:

<button @click="ClickByName()">params传参</button>
ClickByName() {
    
    
	this.$router.push({
    
    
        name: 'B',
		params: {
    
    
			context: '这是一段文字'
		}
	})
}

路由配置:路径后不需要在加上传入的参数,但是name必须和父组件中的name一致

{
    
    path: '/b', name: 'B', component: B}

地址栏中的显示:地址栏不会带有传入的参数,而且再次刷新页面后参数会丢失
http://localhost:8080/#/b

子组件接收参数的方式:

<template>
	<div id="b">
		This is page B!
    <p>传入参数:{
    
    {
    
    this.$route.params.context}}</p>
  </div>
</template>

四、通过query来传递参数

父组件:

<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>这是父组件传入的数据: {
    
    {
    
    this.$route.query.context}}</p>
  </div>
</template>

猜你喜欢

转载自blog.csdn.net/Senora/article/details/125741702