Help us understand the problem. What is going on with this article?

Vue Composition API を使ってリアクティブに値を更新する方法

書かないこと

  • Vue Composition APIの導入方法
  • TypeScriptではなく、Vueのみ
  • refとreactiveの使い分けについて

Vue3.0より実装予定の Composition API を使ってstateの値を更新します。

setup関数内で更新する。

index.vue
<template>
  <div>
    <p>{{ count }}</p>
    <button @click='increment'>+</button>
  </div>
</template>

<script>
  import { ref } from '@vue/composition-api'
  export default {
    setup(){
      const count = ref(0)

      function increment () {
        count.value++
      },
      return{
       increment,
       count
      }
    }
  }
</script>

公式にもある通りですが、シンプルですね。
Vueで値の更新を検知するにはrefを使う必要があります。

Composition Functionで切り出した時の更新

index.vue
<template>
  <div>
    <p>{{ count }}</p>
    <button @click='increment'>+</button>
  </div>
</template>

<script>
  import { ref } from '@vue/composition-api'
  const useIncrement = () => {
    const count = ref(0)

    const increment = () => {
      count.value++
    }
    return {
      increment,
      count
    }
  }
}

  export default {
    setup(){
      const {increment, count } = useIncrement()
      return{
       increment,
       count
      }
    }
  }
</script>

従来のVueではdataやmethodごとに記述箇所が決まっていましたが、
Composition APIを使うことで関数の切り出しが可能になりました。

setup内のstateを更新する。

index.vue
<template>
  <div>
    <p>{{ state.count }}</p>
    <button @click='increment'>+</button>
  </div>
</template>

<script>
  import { ref } from '@vue/composition-api'
  const useIncrement = (state) => {
    const increment = () => {
      state.count++
    }
    return {
      increment
    }
  }
}

  export default {
    setup(){
    const state = reactive({
      count: 0
    })
      const {increment } = useIncrement(state)
      return{
       state,
       increment
      }
    }
  }
</script>

Composition Functionにstateを渡して更新すればOK

VueComposition APIはさわり始めたばかりですが、柔軟コードが書けそうな反面難しそうですね。

参考資料
Vue Composition APIのコラムっぽいもの集

RinT_T
メモみたいにQiitaを書きます。 精度低めです。
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした