Vue路由传参的两种方式

在vue中,参数传递共有2种:

http://localhost:8080/demo?cid=c001

http://localhost:8080/demo2/c001

查询参数

  • 确定访问路径

    <!-- 带查询参数,下面的结果为 /demo?cid=c001 -->

    <router-link to="/demo?cid=c001">Demo</router-link> |

    <router-link :to="{ path: '/demo', query: { cid: 'c001' }}">demo</router-link> 

  • 编写路由

  {

    path: '/demo',

    name: 'demo',

    component: Demo

  },

  • 编写页面,并获得参数

<template>

  <div>

  </div>

</template>

<script>

export default {

    mounted() {

        // 获得查询参数

        console.info( this.$route.query.cid )

    },

}

</script>

<style>

</style>

路径参数

  • 编写访问路径

    <router-link :to="{ name: 'demoName2', params: { uid: 123 }}">Demo2</router-link> |

    <router-link to="/demo2/123">Demo2</router-link> |

  • 确定访问路径

  {

    path: '/demo2/:uid',

    name: 'demoName2',

    component: Demo2

  }

  • 编写路由

{

    path: '/demo2/:uid',

    name: 'demoName2',

    component: Demo2

  } 

  • 编写页面,并获得参数

<template>

  <div>

  </div>

</template>

<script>

export default {

    mounted() {

        // 获得路径参数

        console.info( this.$route.params.uid )

    },

}

</script>

<style>

</style>

路由总结

  • 在任何组件内通过 this.$router 访问路由器
  • 在任何组件内通过 this.$route 访问当前路由:

this.$route相关操作

描述

实例

this.$route.params

获得路径参数

模式       

/user/:uid

匹配路径

/user/123

this.$route.params.uid

123

this.$route.query

获得请求参数

/user?id=123

posted @ 2022-11-09 08:13  陶然同学  阅读(102)  评论(0编辑  收藏  举报