Skip to content

vue3 路由传参

路由跳转

在要跳转的页面引入 useRouter,并实例化 router

js
// 引入
import { useRouter } from 'vue-router'

// 实例化路由
const router = useRouter()

路由跳转的 3 中方式:

js
router.push({ name: 'HistoryPlayback' })

router.push('/sceneRunning/historyPlayback')

router.push({ path: '/sceneRunning/historyPlayback' })

路由传参

传统模式中,路由跳转可以由 3 中方式完成,分别是 query传参、params传参、state传参,但是,在 vue3 中,取消了 params 传参(具体原因可查看文章)。

query 传参

js
router.push({
  path: '/sceneRunning/historyPlayback',
  query: {
    type: SelectTypeEnum.CAR,
    carNum: 'C1234',
    startTime: toRaw(record).startTime,
  },
});
js
import { useRoute } from 'vue-router'
const route = useRoute()

// 获取 query 参数
const data = route.query

state 传参

注意

  1. state 传参时,它所接受的对象中的所有属性必须是 字符串类型,所以这里传递对象时,使用 JSON.stringify() 将其转为字符串;
  2. 在接收参数的一方,使用 JSON.parse() 将参数再次转换为对象;
js
router.push({
  name: 'HistoryPlayback',
  state: {
    carInfo: JSON.stringify(carInfo),
  }
})
js
const state = JSON.parse(history.state.carInfo)

Released under the MIT License.