Getting Started with Vue Router
Vue:2.6
Vue Router:3.3
Vue Router 是 Vue
官方提供的路由管理器,讓前端在操作頁面 route 時更加的方便。由其是要建立 SPA(Single Page Application)
時,更是非常好用的幫手。
Basic Usage
Vue Router
在使用上非常容易,最基本的用法只要將相對應的路徑和 Components
設定好便可以執行。
Notice: 本範例僅使用單一的
index.html
做示範,在其他 Module 化的情況下,設定上會有些許不同。
HTML
...
Hello App!
Go to Foo
Go to Bar
...
Javascript
// 如果是 Moudle 化的用法,記得使用 Vue.use(VueRouter)
// 定義頁面的 Components,也可以透過 import sample.vue 的方式代入頁面
const Foo = { template: 'foo' };
const Bar = { template: 'bar' };
// 定義 Route
const routes = [
{ path: '/foo', component: Foo },
{ path: '/bar', component: Bar }
];
// 建立 Vue Router Instance 並代入設定
const router = new VueRouter({
// 此寫法相當於 routes: routes
routes
});
// 建立 Vue Instance 並代入 router 和綁定 #app
const app = new Vue({
router
}).$mount('#app');
Dynamic Route Matching
既然是 Router
,一定可以動態的支援參數。
範例
// 透過 $route.params 取得參數
const User = { template: 'User:{{ $route.params.username }}' };
const Platform = { template: 'Platform:{{ $route.params.platform }}, User:{{ $route.params.username }}' };
const routes = [
// 定義 :username 參數
// /user/johnsonlu 就會取得 johnsonlu
{ path: '/user/:username', component: User },
// 多個參數
{ path: '/user/:username/platform/:platform', component: Platform},
// 對應到任何路徑,當上面的路徑都沒有對應到時,就會使用此路徑
{ path: '*'}
];
取得 query string
// 透過 $route.query 取得參數
const User = { template: 'User:{{ $route.query.username }}' };
// 定義 Route
const routes = [
// /user?username=johnsonlu
{ path: '/user', component: User }
];
參數也可以設定成 optional
,只要加上 ?
。
範例
// 當參數變成 optional,就算沒有輸入參數也會進到 User page
{ path: '/user/:username?', component: User },
透過 *
和 pathMatch
動態對應參數。
範例
const User = { template: 'User:{{ $route.params.pathMatch }}' };
const routes = [
{ path: '/user-*', component: User },
];
Navigation
在 Vue Router
中,如果想要切換至不同的 url 時,可以使用 router.push()
這個方法。事實上,
在執行時也是呼叫 router.push()
。
範例
const routes = [
{ path: '/foo', component: Foo },
{ path: '/bar', component: Bar },
// 命名路由為 user
{ path: '/user', name: 'user', component: User },
{ path: '*'}
];
// 指接指定路徑
router.push('/bar');
// 設定 path
router.push({path: '/foo'});
// 傳入 username params
router.push({name: 'user', params: {username: 'johnsonlu'}});
// 傳入 username query string
//user?username=johnsonlu
router.push({path: '/user', query: {username: 'johnsonlu'}});
Notice: 在
router.push()
中,當使用path
參數時,params
參數是會被忽略的,因此不能共用。
Nested Routes
Vue Router
也提供巢狀的設定,讓同型態的路由可以用巢狀結構處理。
範例
const User = {
template: `
User:{{ $route.params.id }}
`
};
const Profile = { template: '{{ this.id }} User Profile' };
const Platform = { template: '{{ this.id }} User Platform' };
const routes = [
{
path: '/user/:id',
component: User,
children: [
{
// /user/:id/profile
path: 'profile',
component: Profile
},
{
// /user/:id/platform
path: 'platform',
component: Platform
},
]
}
];
Notice: 其他更進階的應用可以再參考官方文件。
Categories: Vue
Tags: VueVue-Router