一、基礎概念
Vue Router是Vue.js官方的路由管理器,可以讓我們通過組件化的方式構建單頁應用,根據不同的路徑展示不同的組件。在Vue Router中,我們可以通過props屬性將路由參數傳遞給需要展示的組件。
// example import Vue from 'vue' import VueRouter from 'vue-router' Vue.use(VueRouter) const routes = [ { path: '/user/:id', component: User, props: true // 將路由參數作為props傳遞給組件 } ] const router = new VueRouter({ routes }) const User = { props: ['id'], created () { getUser(this.id) } }
二、使用場景
1. 組件內部直接使用
我們可以在組件內部,通過props屬性直接接收路由參數並使用。
// example const User = { props: ['id'], created () { getUser(this.id) } }
2. 組件間傳遞參數
在Vue Router中,我們可以通過props將路由參數傳遞給需要展示的組件。這樣,我們就可以實現組件間傳遞參數的功能。
// 父組件查看用戶信息
// 子組件
{{ user.name }}
原創文章,作者:MRMCL,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/373046.html