Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
0
Help us understand the problem. What is going on with this article?
@RinT_T

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

More than 1 year has passed since last update.

書かないこと

  • 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のコラムっぽいもの集

0
Help us understand the problem. What is going on with this article?
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
RinT_T
メモみたいにQiitaを書きます。 精度低めです。

Comments

No comments
Sign up for free and join this conversation.
Sign Up
If you already have a Qiita account Login
0
Help us understand the problem. What is going on with this article?