Composition API

option APIを使用してコンポーネント内にロジックを書くと、コンポーネントに依存したロジックになってしまい、コンポーネントが大きくなるにつれてメンテナンスし辛くなるというデメリットがあった

その問題を解消するためのComposition APIがある

Composition APIの基本

export default {
  components: { RepositoriesFilters, RepositoriesSortBy, RepositoriesList },
  props: {
    user: {
      type: String,
      required: true
    }
  },
  setup(props) {
    console.log(props) // { user: '' }

    return {} // ここで返されるものはコンポーネントの他のオプションで使用可能
  }
  // 以降、コンポーネントの"他"のオプション
}

Composition APIを使用するにはVueコンポーネントないでsetup を呼び出す必要がある

setupメソッド

リアクティブなデータ reactive または ref

reactiveまたはrefは以前のdataに相当するものです

reactivde

reactiveは1つのオブジェクトとしてデータを定義する

import { reactive } from 'vue';

interface State {
  inputValue: string;
  hasError: boolean;
}
// reactiveの定義
const state = reactive<State>({
  inputValue: '',
  hasError: false
})

// reactiveの値にはオブジェクト形式でアクセスできる
state.inputValue
state.hasError

分割代入するとリアクティブにならない

reactiveを使用する際の注意点として、分割代入した値に対してはリアクティブ性が失われるという点がある

import { reactive } from 'vue';

const { inputValue, hasError } = reactive<State>({
  inputValue: '',
  hasError: false
})