Vue Options APIとCompostion APIの違い

これからVueJSを学ぶ方へ。

VueはReactやAngularと同じようにSPA(Single Page Application)を作るためのJavaScriptフレームワークです。

Reactが統計上では一番人気で求人も多いという事ですが、Vueは初心者にもわかりやすく、数年でReact以上の人気が出ると思います。

現段階ではVueはバージョン3まで出ており、今から始めるなら最新のVue3から学び始めて問題ありません。

Options APIとCompostion API

Options API

Vueのコードを書くにあたり2つ(正確には3つ)方法があります。

一つ目が初心者向けのOptions APIです。

まずはOptionsAPIの例を見てみましょう。

<script>
export default {
  // Properties returned from data() becomes reactive state
  // and will be exposed on `this`.
  data() {
    return {
      count: 0
    }
  },

  // Methods are functions that mutate state and trigger updates.
  // They can be bound as event listeners in templates.
  methods: {
    increment() {
      this.count++
    }
  },

  // Lifecycle hooks are called at different stages
  // of a component's lifecycle.
  // This function will be called when the component is mounted.
  mounted() {
    console.log(`The initial count is ${this.count}.`)
  }
}
</script>

<template>
  <button @click="increment">Count is: {{ count }}</button>
</template>

Options APIの特徴はdata()でデータをまとめmethod()で使用するファンクションをまとめ、このようにブロックごとでコードを分けていくことです。

短所として、thisのキーワードを使わないといけないこと、ブロックごとでコードをまとめるのでコードの文にまとまりがなくなることです。

一応、Options APIという存在があるという事だけ覚えておいて、まったく学ぶ必要はありません。

Composition API

Vueの強みといえるCompostion APIと<script setup>を紹介します。

下記がcompostion APIの例になります。

特徴としては、

  • <script setup>が導入され少ないコードでかけるようになった。
  • setupのキーワードをscriptタグに入れた場合はvueからメソッドをインポートする必要があります。
  • 機能ごとにコードをまとめるので後から読みやすい。
  • インポートしたコンポーネントや変数をそのままHTMLのテンプレートで使用できる。
<script setup>
import { ref, onMounted } from 'vue'

// reactive state
const count = ref(0)

// functions that mutate state and trigger updates
function increment() {
  count.value++
}

// lifecycle hooks
onMounted(() => {
  console.log(`The initial count is ${count.value}.`)
})
</script>

<template>
  <button @click="increment">Count is: {{ count }}</button>
</template>

ではrefやonMountのLifecycle Hook(ライフサイクルフック)は今後、基本のコンポーネントやプロップの使い方を紹介した後に詳しく説明していきたいと思います。

今日、覚えてほしいことです。

  • VueはCompostion APIの書き方で書くようにする。
  • VueはJavaScriptとhtml、cssが一つのファイルにまとまった.vueファイルで構成される。