# ルーティング
# 公式ルータ
ほとんどのシングルページアプリケーションでは、公式にサポートされている vue-router ライブラリ (opens new window)を使うことをオススメします。詳細は vue-router のドキュメント (opens new window)を参照してください。
# スクラッチからのシンプルなルーティング
とてもシンプルなルーティングだけが必要で、フル機能のルータライブラリを使用したくない場合は、以下のようにページレベルのコンポーネントで動的にレンダリングができます。
const NotFoundComponent = { template: '<p>Page not found</p>' }
const HomeComponent = { template: '<p>Home page</p>' }
const AboutComponent = { template: '<p>About page</p>' }
const routes = {
'/': HomeComponent,
'/about': AboutComponent
}
const SimpleRouter = {
data: () => ({
currentRoute: window.location.pathname
}),
computed: {
CurrentComponent() {
return routes[this.currentRoute] || NotFoundComponent
}
},
render() {
return Vue.h(this.CurrentComponent)
}
}
Vue.createApp(SimpleRouter).mount('#app')
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
History API (opens new window) と組み合わせることで、とても基本的ですが完全に機能するクライアント側のルータを構築できます。実際に確認するには、このサンプルアプリ (opens new window)をチェックしてみてください。
# サードパーティ製ルータとの統合
Page.js (opens new window) や Director (opens new window) のようなサードパーティ製のルータを使いたい場合は、統合は同様に簡単 (opens new window)です。ここに、Page.js を使ったサンプル (opens new window)があります。
← TypeScript のサポート 状態管理 →