在Vue3中进行页面跳转并携带参数,有多种方案,以下是常见的几种:

  1. 使用路由的params参数:将参数放在路由的路径中,适合必传参数,且参数是路径的一部分。

  2. 使用路由的query参数:将参数以查询字符串的形式附加在URL后面,适合可选参数。

  3. 使用Vuex或Pinia(状态管理):将参数存储在全局状态中,跳转页面后从状态中读取,适合参数较多或不想在URL中暴露的情况。

主要推荐前两种,因为它们是Vue Router官方支持且最常用的方式。

1. 路由参数(Params)

1.1 动态路由参数

// 路由配置
{
  path: '/user/:id',
  name: 'UserDetail',
  component: UserDetail
}

// 跳转时传递参数
router.push('/user/123')
// 或
router.push({ name: 'UserDetail', params: { id: 123 } })

// 目标页面获取参数
import { useRoute } from 'vue-router'
const route = useRoute()
const userId = route.params.id

1.2 非动态路由参数

// 路由配置不需要特殊设置
router.push({ name: 'UserList', params: { page: 1, filter: 'active' } })

// 目标页面获取
const route = useRoute()
const page = route.params.page

注意:使用 params 时,如果使用 path 跳转,params 会被忽略。

2. 查询参数(Query)

// 跳转时传递查询参数
router.push('/user?page=1&filter=active')
// 或
router.push({
  path: '/user',
  query: {
    page: 1,
    filter: 'active'
  }
})
// 或
router.push({
  name: 'UserList',
  query: {
    page: 1,
    filter: 'active'
  }
})

// 目标页面获取查询参数
const route = useRoute()
const page = route.query.page
const filter = route.query.filter

3. 状态管理(Pinia/Vuex)

// store/user.js (Pinia示例)
import { defineStore } from 'pinia'

export const useUserStore = defineStore('user', {
  state: () => ({
    userData: null,
    tempParams: {}
  }),
  actions: {
    setTempParams(params) {
      this.tempParams = params
    }
  }
})

// 跳转前存储参数
import { useUserStore } from '@/stores/user'
const userStore = useUserStore()
userStore.setTempParams({ userId: 123, type: 'detail' })
router.push('/user/detail')

// 目标页面获取参数
const userStore = useUserStore()
const params = userStore.tempParams

4.总结

  • 如果参数是少量且希望体现在URL中,使用params或query。
  • 如果参数较多或敏感,不想在URL中暴露,使用状态管理或本地存储。

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐