概要
Vue.jsでURLに応じて複数のページの表示を切り替える。
バージョン情報
- "vue": "^2.6.11"
- "vue-router": "^3.4.8"
- @vue/cli 4.5.7
プロジェクトフォルダの作成
$ vue create routing-example $ cd routing-example
vue-routerのインストール
$ yarn add vue-router ansi-regex
vue.config.js の記述
下記のようなエラーに対応するため、プロジェクトの直下に vue.config.js を記載しておく。
[Vue warn]: You are using the runtime-only build of Vue where the template compiler is not available. Either pre-compile the templates into render functions, or use the compiler-included build
内容は下記。
module.exports = { configureWebpack: { resolve: { alias: { 'vue$': 'vue/dist/vue.esm.js' } } } }
routingの記述
src/routes.js にroutingの記述。
/ なら Homeに、/about なら About に遷移するような記述。
import Vue from 'vue' import VueRouter from 'vue-router' Vue.use(VueRouter) const Home = { template: '<p>home page</p>' } const About = { template: '<p>about page</p>' } const routes = [ { path: '/', component: Home }, { path: '/about', component: About } ] export default new VueRouter({ mode: 'history', routes, })
src/main.js に呼び出し部分を記述
import Vue from 'vue' import router from './router' Vue.config.productionTip = false new Vue({ router }).$mount('#app')
public/index.html にrouterの表示部分として router-view を記述。
<!DOCTYPE html> <html lang="ja"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width,initial-scale=1.0"> <link rel="icon" href="<%= BASE_URL %>favicon.ico"> <title><%= htmlWebpackPlugin.options.title %></title> </head> <body> <noscript> <strong>We're sorry but <%= htmlWebpackPlugin.options.title %> doesn't work properly without JavaScript enabled. Please enable it to continue.</strong> </noscript> <div id="app"> <router-view></router-view> </div> </body> </html>
サーバーを実行して内容を確認。
$ yarn run serve
/ をリクエストした場合と /aboutをリクエストした場合で表示されるコンポーネントが変わる。
また指定されていないパス(ここでは /other)をリクエストした場合は空が表示される。
Not Foundのページ指定
ステータスコードとかは気にせず単純にnot foundとだけ表示する例。
routesの記載に当てはまらないものはすべてNotFoundページに飛ばす。
const Home = { template: '<p>home page</p>' } const About = { template: '<p>about page</p>' } const NotFound = { template: '<p>not found page</p>' } const routes = [ { path: '/', component: Home }, { path: '/about', component: About }, { path: '*', component: NotFound } ]
ステータスコードで404を返す場合はサーバー側で。
リンクの記述
homeとaboutを行き来できるよう public/index.html にリンクを追加する
<div id="app"> <router-view></router-view> <router-link to="/">Home</router-link> <router-link to="/about">About</router-link> </div>
componentに記述してパラメータを渡す
HomeとAboutをcomponentに記述して、ついでにクエリパラメータの受け渡しをしてみる。
src/components/Home.vue の記述。こちらはただhome pageと表示するのみ。
<template> <div id="home"> home page </div> </template> <script> export default { name: 'Home', } </script>
src/components/About.vue の記述。こちらはmsgというプロパティを持つ。
<template> <div id="about"> about {{ msg }} page </div> </template> <script> export default { name: 'About', props: { msg: String } } </script>
src/router.js の記述。 /about ではクエリストリングの msg という
const routes = [ { path: '/', component: () => import("./components/Home") }, { path: '/about', component: () => import("./components/Home"), props: (route) => ({ msg: route.query.msg }) }, { path: '*', component: NotFound } ]
publlic/index.html の router-link の内容を書き換えてクエリパラメータを渡すようにする。
<div id="app"> <router-view></router-view> <router-link to="/">Home</router-link> <router-link v-bind:to="{path: '/about', query: {msg: 'message'}}">About</router-link> </div>
これでパラメータを引き渡すリンクが作成できた。
改定履歴
Author: Masato Watanabe, Date: 2020-11-03, 記事投稿