欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

在Vue中实现路由传递参数的两种方法

最编程 2024-08-01 19:35:02
...

查询参数


  • 确定访问路径
  <!-- 带查询参数,下面的结果为 /demo?cid=c001 -->

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

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

编写路由 微信图片_20220524130007.png

  {

    path: '/demo',

    name: 'demo',

    component: Demo

  },
  • 编写页面,并获得参数

<template>

<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

  }

编写路由

微信图片_20220524130215.png

{

    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 访问当前路由: image.png