Skip to content

查询字符串和路径传递参数

字符串传递参数query

使用查询字符串来传递参数比较常见,查询字符串就是在路径地址后面加上一个?,再带上参数,如:http://localhost:5173/?id=100&title=详情内容,当然这个字符串是可以随便自定义的,但是地址中的字符串是什么,在接收的组件中就要对应写什么,也可以不给所有的查询字符串都传递参数

vue
// 可以在文件中传递参数
<RouterLink 
  :to="{
    //name:'xiang', //用name也可以跳转
    path:'/news/detail',
    query:{
      id:news.id,
      title:news.title,
      content:news.content
    }
  }"
>
{{news.title}}
</RouterLink>

我们在这个被访问的组件下通过以下的方式就可以看到传递的参数值

vue
<template>
    id: {{ $route.query.id }}
    title: {{ $route.query.title }}
</template>

<script setup>
import { useRoute } from 'vue-router'
const route = useRoute()
console.log(route.query)
</script>

路径传递参数params

路径传递参数,就需要在router/index.js文件中,对path进行内容的添加从而传递参数:path: '/CodeAndCesium/:id/title/:title'

在访问地址中通过http://localhost:5173/codeAndCesium/007/name/在线编译器方式就可以将要传递的内容007和在线编译器进行传递,同时在接收参数的组件中进行参数的接收

但是这种方法是在路径上进行修改,必须要保证访问的路径和对应的路由规则是相同的,不然是访问不到正确的页面的,如果我们不想要传递title参数,我们只需要在其后面加个?path: '/CodeAndCesium/:id/title/:title?',在地址栏输入:http://localhost:5173/codeAndCesium/007/title即可不传递title参数进行访问

vue
//也可以在文件中进行传递参数
<RouterLink 
  :to="{
    name:'xiang', //传递params参数时,若使用to的对象写法,只能用name配置项,不能用path
    params:{
      id:news.id,
      title:news.title,
      content:news.title
    }
  }"
>
  {{news.title}}
</RouterLink>
js
//接收参数文件
import {useRoute} from 'vue-router'
const route = useRoute()
// 打印params参数
console.log(route.params)

Released under the MIT License.