温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

vue路由传值的方式有哪些

发布时间:2021-09-14 12:14:38 来源:亿速云 阅读:170 作者:小新 栏目:编程语言

这篇文章给大家分享的是有关vue路由传值的方式有哪些的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。

vue路由传值的方式:1、利用“router-link”路由导航来传递;2、调用“$router.push”实现路由传参数值;3、通过路由属性中的name匹配路由,再根据params传递参数值;4、通过query来传递参数值。

本教程操作环境:windows7系统、vue2.9.6版,DELL G3电脑。

vue路由传参值的方法

一、router-link路由导航

父组件: 使用<router-link to = "/跳转路径/传入的参数"></router-link>

例如:<router-link to="/a/123">routerlink传参</router-link>

子组件: this.$route.params.num接收父组件传递过来的参数

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

路由配置:{path: '/a/:num', name: A, component: A}

地址栏中的显示:http://localhost:8080/#/a/123

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

父组件: 绑定点击事件,编写跳转代码

<button @click="deliverParams(123)">push传参</button>
  methods: {
    deliverParams (id) {
      this.$router.push({
        path: `/d/${id}`
      })
    }
  }

子组件: this.$route.params.id接收父组件传递过来的参数

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

路由配置:{path: '/d/:id', name: D, component: D}

地址栏中的显示:http://localhost:8080/#/d/123

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

父组件: 匹配路由配置好的属性名

<button @click="deliverByName()">params传参</button>
    deliverByName () {
      this.$router.push({
        name: 'B',
        params: {
          sometext: '一只羊出没'
        }
      })
    }

子组件:

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

路由配置: 路径后面不需要再加传入的参数,但是name必须和父组件中的name一致
{path: '/b', name: 'B', component: B}

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

四、通过query来传递参数

父组件:

<button @click="deliverQuery()">query传参</button>
    deliverQuery () {
      this.$router.push({
        path: '/c',
        query: {
          sometext: '这是小羊同学'
        }
      })
    }

子组件:

<template>
  <div id="C">
    This is page C!
    <p>这是父组件传入的数据: {{this.$route.query.sometext}}</p>
  </div>
</template>

路由配置: 不需要做任何修改
{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

感谢各位的阅读!关于“vue路由传值的方式有哪些”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识,如果觉得文章不错,可以把它分享出去让更多的人看到吧!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

vue
AI