1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Vue Routerを使ってみた

Posted at

Vueのプロジェクト作成からVue Routerを構築する手順を記載します。

Vue Routerの導入

まず、Vueプロジェクトを作成します。

vue create [プロジェクト名]

Vueプロジェクト作成時にVue Roterを組み込む場合は、Manually select featuresを選択します。

Vue CLI v4.5.15
? Please pick a preset: 
  Default ([Vue 2] babel, eslint) 
  Default (Vue 3) ([Vue 3] babel, eslint) 
❯ Manually select features 

必要なモジュールを選択します。
Routerを選択します。

Vue CLI v4.5.15
? Please pick a preset: Manually select features
? Check the features needed for your project: 
 ◉ Choose Vue version
 ◉ Babel
 ◯ TypeScript
 ◯ Progressive Web App (PWA) Support
❯◉ Router
 ◉ Vuex
 ◯ CSS Pre-processors
 ◉ Linter / Formatter
 ◯ Unit Testing
 ◯ E2E Testing

バージョンを選択します。

? Choose a version of Vue.js that you want to start the project with (Use arrow 
keys)
❯ 2.x 
  3.x 

ヒストリーモードかどうかを選択します。

? Use history mode for router? (Requires proper server setup for index fallback 
in production) (Y/n) 

ここではYを入力しました。

linterおよびタイミングを選択します。(オプションで選択した場合)

? Pick a linter / formatter config: (Use arrow keys)
❯ ESLint with error prevention only
  ESLint + Airbnb config
  ESLint + Standard config
  ESLint + Prettier
? Pick additional lint features: (Press <space> to select, <a> to toggle all, <i
> to invert selection)
❯◉ Lint on save
 ◯ Lint and fix on commit

各設定ファイルをどこに作成するかを選択します。
ここではIn package.jsonを選択しました。

? Where do you prefer placing config for Babel, ESLint, etc.? (Use arrow keys)
  In dedicated config files 
❯ In package.json

最後に設定を保存するかを聞かれます。

Save this as a preset for future projects? (y/N) 

Vueプロジェクトが作成されました。
表示されている通り、コマンドを入力すれば実行されます。

🎉  Successfully created project vue-router-test.
👉  Get started with the following commands:

 $ cd vue-router-test
 $ npm run serve

npm run serveを実行し、App running atに表示されているURLにアクセスすると、Vueの初期面が表示されます。

Vue.png

Vue routerの構成

main.js

main.jsにrouterが追加されています。

src/main.js
new Vue({
  router,
  store,
  render: (h) => h(App),
}).$mount("#app");

router/index.js

src配下にrouter/index.jsにrouterが追加されています。

src/router/index.js
import Vue from "vue";
import VueRouter from "vue-router";
import Home from "../views/Home.vue";

Vue.use(VueRouter);

const routes = [
  {
    path: "/",
    name: "Home",
    component: Home,
  },
  {
    path: "/about",
    name: "About",
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () =>
      import(/* webpackChunkName: "about" */ "../views/About.vue"),
  },
];

const router = new VueRouter({
  mode: "history",
  base: process.env.BASE_URL,
  routes,
});

export default router;

初期ではルート//aboutが記載されており、ルートはHome、AboutはAbout.vueがcomponentに指定されています。
HomeはHome.vueがimport文にて定義されており、Aboutはcomponentにimport文が直書きされています。
Aoubtの書き方はコメントにもある通り、lazy-loadedでコンポーネントを読み込むやり方です。
lazy-loadedの場合は、ページ遷移した時に初めてコンポーネントが読み込まれるようになっており、
初期段階でコンポーネントを読み込むよりも、ページが重くならないようです。

上記の場合、ルートのURLにアクセスした場合はHome.vueが表示され、/aboutにアクセスした場合はAbout.vueが表示されます。

App.vue

またApp.vueにはrouter-linkが定義されています。

src/App.vue
<template>
  <div id="app">
    <div id="nav">
      <router-link to="/">Home</router-link> |
      <router-link to="/about">About</router-link>
    </div>
    <router-view />
  </div>
</template>

先ほど表示した画面の上部を見てみると、HomeとAboutのリンクが表示されています。
AboutをクリックするとAbout.vueの内容が表示され、Homeをクリックすると先程のHome画面が表示されます。

About.png

Routeへの追加

次は新しくvueファイルを作成して、routeへ追加してみます。
src/viewsの中に新しくHoge.vueを追加します。中身はAbout.vueとほぼ同じです。

src/views/Hoge.vue
<template>
  <div class="hoge">
    <h1>This is an hoge page</h1>
  </div>
</template>

router/index.jsのAboutの下にHogeのroute情報を追加します。

src/router/index.js
  {
    path: "/hoge",
    name: "Hoge",
    component: () =>
      import(/* webpackChunkName: "hoge" */ "../views/Hoge.vue"),
  },

またApp.vueのリンクにHogeを追加します。

src/App.vue
      <router-link to="/">Home</router-link> |
      <router-link to="/about">About</router-link> |     ← `|`を追記
      <router-link to="/hoge">Hogeのページ</router-link>   ← 追加
    </div>

npm run serveにて起動し、アクセスするとHogeのページが増えています。

App.png

クリックするとHoge.vueの内容が表示されます。

Hege.png

Vue routerの基本的な構成について説明しました。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?