vue-参数传递

  之前学习过动态路由的参数传递,属于URL占位符的方式,取的话是通过$route.params来取的;其实还有一种参数传递的方式,就是传统的URL后面跟着参数的形式,话不多说,还是写代码吧:

<template>
  <div id="nav">
    <router-link :to="{path: '/profile',query: {name: 'zhangsan',age: 89}}">Profile</router-link>
  </div>
  <router-view/>
</template>

  到时候点击该路由链接时,在地址栏的路径是这样的:

http://localhost:8080/profile?name=zhangsan&age=89

  要想取到这里面的参数,在跳转的组件里,得通过$route.query的方式,如下:

<template>
  <div>
    <h1>我是Profile</h1>
    <h1>接收到的参数{{$route.query.name}}</h1>
    <h1>接收到的参数{{$route.query.age}}</h1>
  </div>
</template>

  其实就差不多这些了,但还得讲一个关于代码的路由跳转的方式,之前代码的路由跳转是这样的:

this.$router.push('/profile')

  其实还有一种对象字面量的写法:

    this.$router.push({
      path: '/profile',
      query: {
        name: 'zhangsan',
        age: 18
      }
    })

  这种方式也能跳转到对应的路径,并且该写法可读性更好,用得也挺多的

  总结吧:如果是RestFul风格的参数传递且参数较少,那就是params的用法;若还是传统且参数较多的方式,那就是query

原文地址:https://www.cnblogs.com/ibcdwx/p/14606250.html