欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Vue Router中獲取路由傳遞過來的參數(shù)(方法詳解)

 更新時間:2025年02月06日 16:08:25   作者:Kris-L-  
在VueRouter中,可以通過動態(tài)路由匹配和查詢參數(shù)`query`來傳遞參數(shù),并將路由參數(shù)或查詢參數(shù)作為組件的`props`傳遞,動態(tài)路由匹配使用`route.params`訪問參數(shù),查詢參數(shù)使用`route.query`訪問,本文給大家介紹Vue Router中獲取路由傳遞過來的參數(shù),感興趣的朋友一起看看吧

在Vue Router中可以通過動態(tài)路由匹配和查詢參數(shù)query來傳遞參數(shù);同時也可以將路由參數(shù)或查詢參數(shù)作為組件的props傳遞,這樣組件可以直接通過props來訪問這些參數(shù)。

1. 動態(tài)路由匹配

如果在路由配置中使用了動態(tài)路由(如/user/:id),則可以通過route.params.id獲取該參數(shù)。

// 路由配置
const routes = [
  { path: '/user/:id', component: User }
];
// 組件中獲取參數(shù)
<script setup>
import { useRoute } from 'vue-router';
const route = useRoute();
const userId = route.params.id;
</script>

2. 查詢參數(shù)query

如果URL中有查詢字符串(如/user?id=123)或路由跳轉(zhuǎn)時寫了query【如router.push({path: ‘/user’,query: { id: 123}});】,則可以通過route.query.id獲取該參數(shù)。

// 路由配置
const routes = [
  { path: '/user', component: User }
];
// 組件中獲取參數(shù)
<script setup>
import { useRoute } from 'vue-router';
const route = useRoute();
const userId = route.query.id;
</script>

3. 通過 props 傳遞參數(shù)

在路由配置中啟用 props,并將 params 作為 props 傳遞。

// 路由配置
const routes = [
  { path: '/user/:id', component: User, props: true }
];
// 組件中通過 props 獲取參數(shù)
<script setup>
import { defineProps, onMounted } from 'vue';
const props = defineProps({
  id: {
    type: String,
    required: true
  }
});
onMounted(() => {
  console.log(props.id);
});
</script>

通過 props 傳遞查詢參數(shù)。

// 路由配置
const routes = [
  { path: '/user', component: User, props: (route) => ({ id: route.query.id }) }
];
// 組件中通過 props 獲取參數(shù)
<script setup>
import { defineProps, onMounted } from 'vue';
const props = defineProps({
  id: {
    type: String,
    required: true
  }
});
onMounted(() => {
  console.log(props.id);
});
</script>

到此這篇關(guān)于Vue Router中獲取路由傳遞過來的參數(shù)(方法詳解)的文章就介紹到這了,更多相關(guān)Vue Router路由參數(shù)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論