日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 前端技术 > vue >内容正文

vue

vue-router 动态路由匹配

發布時間:2024/9/27 vue 29 豆豆
生活随笔 收集整理的這篇文章主要介紹了 vue-router 动态路由匹配 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

目錄

  • 1. 動態匹配路由的基本用法
  • 2. 路由組件傳遞參數
    • 2.1 props 的值為布爾類型
    • 2.2 props 的值為對象類型
    • 2.3 props的值為函數類型


1. 動態匹配路由的基本用法

【應用場景】:通過動態路由 參數 的模式進行路由匹配。

var router = new VueRouter({routes: [// 動態路徑參數 以冒號開頭{ path: '/user/:id', component: User }] })

即在路由規則中,把動態的部分在前面加上冒號(:), 冒號就代表當前這個位置匹配的是動態參數,匹配成功后,在 User組件中就可以訪問到當前匹配到的 id 值。

那么,如何來訪問這個id值呢?請看下面的語法,我們是通過 $route.params 這個對象 獲取到這個動態匹配到的路由參數。

const User = {// 路由組件中通過 $route.params 獲取路由參數template: '<div>User {{ $route.params.id }}</div>' }

2. 路由組件傳遞參數

$route與對應路由形成高度耦合,不夠靈活,所以可以使用props將組件和路由解耦。

2.1 props 的值為布爾類型

const router = new VueRouter({routes: [// 如果 props 被設置為 true,route.params 將會被設置為組件屬性{ path: '/user/:id', component: User, props: true}] })const User = {props: ['id'], // 使用 props 接收路由參數template: '<div> 用戶 ID:{{ id }} </div>' // 使用路由參數 }

props: true:表示給這個規則開啟了傳參;
props: ['id'] :定義了 id 這個路由參數。

2.2 props 的值為對象類型

const router = new VueRouter({routes: [// 如果 props 是一個對象,它會被按原樣設置為組件屬性{ path: '/user/:id', component: User, props: { uname: 'lisi', age: 12 }}]})const User = {props: ['uname', 'age'],template:<div>用戶信息:{{ uname + '---' + age}}</div>' }

2.3 props的值為函數類型

const router = new VueRouter({routes: [// 如果 props 是一個函數,則這個函數接收 route 對象為自己的形參{ path: '/user/:id',component: User,props: route => ({uname: 'zs', age: 20, id: route.params.id })}] })const User = {props: ['uname', 'age', 'id'],template:<div>用戶信息:{{ uname + '---' + age + '---' + id}}</div>' }

注: ,props: route => 這里的 route 即是路由中的動態參數對象,:id中有幾個參數項,則route中就有幾個參數值。那么,在箭頭函數的函數體中,可以返回一個props對象。 id 值就可通過route動態匹配:id 獲取(id: route.params.id)

總結

以上是生活随笔為你收集整理的vue-router 动态路由匹配的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。