千鋒教育前端Vue3.0全套視頻教程(Kerwin2023版,Vue.js零基礎(chǔ)
2023-07-21 09:56 作者:bili_78585383517 | 我要投稿

在 Vue.js 中,可以使用 Vue Router 來實現(xiàn)動態(tài)路由匹配。Vue Router 提供了一種靈活的方式來根據(jù)不同的參數(shù)動態(tài)生成和匹配路由。:
1.創(chuàng)建一個router文件夾 在他下面在創(chuàng)建的index.js文件。
2.定義動態(tài)路由:
在路由配置文件中,使用冒號?:id 或許 :usename 來表示動態(tài)參數(shù),這些參數(shù)將作為路由路徑的一部分。
const router = new VueRouter({ routes: [ { path: '/usename/:id', component: Usename, }, ] });
3.定義動態(tài)參數(shù)的組件:
為動態(tài)參數(shù)的組件書寫對應(yīng)的 Vue 組件。在組件內(nèi)部,可以通過?$router.params?可以訪問傳遞的動態(tài)參數(shù)。
<template> <div> User {{ $route.params.id }} </div> </template> <script> export default { name: 'Username', } </script>
4使用動態(tài)路由:
在需要進(jìn)行動態(tài)路由匹配的地方,使用?<router-link>或?router.push()?來生成帶有動態(tài)參數(shù)的鏈接??梢栽趓outer.push()中輸入你要跳轉(zhuǎn)頁面的路徑,寫法1.this.$router.push( `/usename/${id}`);寫法2:this.$router.push({
name:"Usename",
params:{
myid:id
})
動態(tài)路由配置中的?/usename:id可以匹配任意的?/usename?后面跟著的參數(shù)值,這些參數(shù)值可以通過?$route.params?在組件中訪問到。
標(biāo)簽: