vue-router 动态路由匹配
生活随笔
收集整理的這篇文章主要介紹了
vue-router 动态路由匹配
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
目錄
- 1. 動態(tài)匹配路由的基本用法
- 2. 路由組件傳遞參數(shù)
- 2.1 props 的值為布爾類型
- 2.2 props 的值為對象類型
- 2.3 props的值為函數(shù)類型
1. 動態(tài)匹配路由的基本用法
【應(yīng)用場景】:通過動態(tài)路由 參數(shù) 的模式進(jìn)行路由匹配。
var router = new VueRouter({routes: [// 動態(tài)路徑參數(shù) 以冒號開頭{ path: '/user/:id', component: User }] })即在路由規(guī)則中,把動態(tài)的部分在前面加上冒號(:), 冒號就代表當(dāng)前這個位置匹配的是動態(tài)參數(shù),匹配成功后,在 User組件中就可以訪問到當(dāng)前匹配到的 id 值。
那么,如何來訪問這個id值呢?請看下面的語法,我們是通過 $route.params 這個對象 獲取到這個動態(tài)匹配到的路由參數(shù)。
const User = {// 路由組件中通過 $route.params 獲取路由參數(shù)template: '<div>User {{ $route.params.id }}</div>' }2. 路由組件傳遞參數(shù)
$route與對應(yīng)路由形成高度耦合,不夠靈活,所以可以使用props將組件和路由解耦。
2.1 props 的值為布爾類型
const router = new VueRouter({routes: [// 如果 props 被設(shè)置為 true,route.params 將會被設(shè)置為組件屬性{ path: '/user/:id', component: User, props: true}] })const User = {props: ['id'], // 使用 props 接收路由參數(shù)template: '<div> 用戶 ID:{{ id }} </div>' // 使用路由參數(shù) }props: true:表示給這個規(guī)則開啟了傳參;
props: ['id'] :定義了 id 這個路由參數(shù)。
2.2 props 的值為對象類型
const router = new VueRouter({routes: [// 如果 props 是一個對象,它會被按原樣設(shè)置為組件屬性{ path: '/user/:id', component: User, props: { uname: 'lisi', age: 12 }}]})const User = {props: ['uname', 'age'],template: ‘<div>用戶信息:{{ uname + '---' + age}}</div>' }2.3 props的值為函數(shù)類型
const router = new VueRouter({routes: [// 如果 props 是一個函數(shù),則這個函數(shù)接收 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 即是路由中的動態(tài)參數(shù)對象,:id中有幾個參數(shù)項(xiàng),則route中就有幾個參數(shù)值。那么,在箭頭函數(shù)的函數(shù)體中,可以返回一個props對象。 id 值就可通過route動態(tài)匹配:id 獲取(id: route.params.id)
總結(jié)
以上是生活随笔為你收集整理的vue-router 动态路由匹配的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 原生JavaScript轮播图效果实现
- 下一篇: 大事件后台管理系统开发实战(下)