Vue.js/Nuxt.jsで画面遷移

pagesディレクトリに作成したvueファイルはすべて自動的にルーティングに登録される!
すばらしい♪

ページ作成

sampleレイアウトで会社概要ページとお問い合わせページを作成。

pages/about.vue

<template>
  <section class="container">
    <h2>会社概要</h2>
    <div>会社概要ページです。</div>
  </section>
</template>

<script>
export default {
  layout: 'sample',
}
</script>

お問い合わせページ
pages/contact.vue

<template>
  <section class="container">
    <h2>お問い合わせ</h2>
    <div>お問い合わせページです。</div>
  </section>
</template>

<script>
export default {
  layout: 'sample',
}
</script>

画面遷移のリンク作成

コンポーネントのSampleHeder.vueを修正。

<nuxt-link to=”[url]”>でアンカーリンクが作成されるのね。

components/SampleHeader.vue

<template>
  <div class="header">
    <h1>Nuxt.js Sample!</h1>
    <ul class="menu">
      <li><nuxt-link to="/">トップ</nuxt-link></li>
      <li><nuxt-link to="/about">会社概要</nuxt-link></li>
      <li><nuxt-link to="/contact">お問い合わせ</nuxt-link></li>
    </ul>
  </div>
</template>

<style>
.menu {
  list-style: none;
  padding: 0;
  background-color: #EEE;
}
.menu li {
  display: inline-block;
  padding: 5px;
}
</style>

動的ルーティング

pagesディレクトリ以下でファイル名またはディレクトリ名にアンダースコアのプレフィックスを付けることで動的ルーティングが自動生成されるよ。

例えば、http://localhost:3000/user/[ID] で[ID]が動的に変化する場合

[ID]は $route.params.id で取得できる。

pages/user/_id.vue

<template>
  <section class="container">
    <h2>ID</h2>
    <div>IDは{{ $route.params.id }}です。</div>
  </section>
</template>

<script>
export default {
  layout: 'sample',
  head: {
    title: '動的ルーティング',
    meta: [
      {
        hid: 'description', name: 'description', content: '動的ルーティングのサンプルです。'
      }
    ]
  },
}
</script>

<style>
</style>

※export文で使用するときはthisが必要なのね。

pages/user/_id.vue

<div>IDは{{ id }}です。</div>
・・・
<script>
export default {
  data() {
    return {
      id: this.$route.params.id
    }
  },
}
</script>