vue3中路由傳參query、params及動態(tài)路由傳參詳解
一、query傳參
編程式導航 使用router.push
或者 router.replace
的時候,改為對象形式新增query
必須傳入一個對象
import { useRouter } from 'vue-router'; ... const router = useRouter() const toDetail = (item: Item) => { router.push({ path: '/info', query: item }) }
接受參數(shù)
使用 useRoute
的 query
<template> <div> <div>ID:{{route.query?.id}}</div> <div>名稱:{{route.query?.name}}</div> <div>價格:{{route.query?.price}}</div> </div> </template> <script setup lang='ts'> import { useRoute } from 'vue-router'; ... const route = useRoute() </script> <style lang='less' scoped> </style>
二、params傳參
編程式導航 使用router.push
或者 router.replace
的時候,改為對象形式并且只能使用name
,path無效,然后傳入params
import { useRouter } from 'vue-router'; ... const router = useRouter() const toDetail = (item: Item) => { router.push({ name: 'Info', params: item }) }
接受參數(shù)
使用 useRoute
的 params
<template> <div> <div>ID:{{route.params?.id}}</div> <div>名稱:{{route.params?.name}}</div> <div>價格:{{route.params?.price}}</div> </div> </template> <script setup lang='ts'> import { useRoute } from 'vue-router'; ... const route = useRoute() </script> <style lang='less' scoped> </style>
三、動態(tài)傳參
很多時候,我們需要將給定匹配模式的路由映射到同一個組件。
例如,我們可能有一個 User 組件,它應(yīng)該對所有用戶進行渲染,但用戶 ID 不同。在 Vue Router 中,我們可以在路徑中使用一個動態(tài)字段來實現(xiàn),我們稱之為 路徑參數(shù)
// router.ts import { createRouter, createWebHistory, RouteRecordRaw } from "vue-router"; const routes: Array<RouteRecordRaw> = [{ path: '/', name: 'table', component: () => import('@/view/Table/index.vue') }, { path: '/info/:id', name: 'Info', component: () => import('@/view/Table/info.vue') }, ... ] const router = createRouter({ history: createWebHistory(), routes }) export default router
import { useRouter } from 'vue-router'; ... const router = useRouter() const toDetail = (item: Item) => { router.push({ name: 'Info', params: {id: item.id} }) }
接受參數(shù)
使用 useRoute
的 params
<template> <div> <div>ID:{{ item?.id }}</div> <div>名稱:{{ item?.name }}</div> <div>價格:{{ item?.price }}</div> </div> </template> <script setup lang='ts'> import { useRoute } from 'vue-router'; import { data } from './data.json' ... const route = useRoute() // 模擬根據(jù)id獲取數(shù)據(jù) const item = data.find(v => v.id === Number(route.params.id)) </script> <style lang='less' scoped> </style>
四、query傳參和params傳參的區(qū)別
- query 傳參配置的是 path,而 params 傳參配置的是name,且在 params中配置 path 無效
- query傳遞的參數(shù)會顯示在地址欄中,而params傳參不會
- query傳參刷新頁面數(shù)據(jù)不會消失,而params傳參刷新頁面數(shù)據(jù)回消失
- params可以使用動態(tài)傳參,動態(tài)傳參的數(shù)據(jù)會顯示在地址欄中,且刷新頁面不會消失,因此可以使用動態(tài)params傳參,根據(jù)動態(tài)傳遞參數(shù)在傳遞頁面獲取數(shù)據(jù),以防頁面刷新數(shù)據(jù)消失
總結(jié)
到此這篇關(guān)于vue3中路由傳參query、params及動態(tài)路由傳參的文章就介紹到這了,更多相關(guān)vue3路由傳參query params內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
vue 設(shè)置proxyTable參數(shù)進行代理跨域
這篇文章主要介紹了vue 設(shè)置proxyTable參數(shù)進行代理跨域的相關(guān)資料,及代理跨域的概念原理,需要的朋友可以參考下2018-04-04Vue.js獲取手機系統(tǒng)型號、版本、瀏覽器類型的示例代碼
這篇文章主要介紹了vue js獲取手機系統(tǒng)型號、版本、瀏覽器類型的示例代碼,代碼簡單易懂,非常不錯具有一定的參考借鑒價值,需要的朋友可以參考下2020-05-05