サイトアイコン 上尾市のWEBプログラマーによるブログ

[Vue.js3] Composition APIのわかりやすい解説

Vue.js

概要

Vue.js 3から導入されたComposition APIについて、簡単にまとめました。

Composition API

Composition APIの記述方法

糖衣構文の場合

<script setup>
import { ref } from 'vue'

const count = ref(0)
const countUp = () => {
  count.value++
}
</script>
<template>
  <h1 @click="countUp">{{ count }}</h1>
</template>

糖衣構文を使わない場合

<script>
import { ref } from 'vue'

export default ({
  setup() {
    const count = ref(0)
    const countUp = () => {
      count.value++
    }
    return { count, countUp }
  }
})
</script>
<template>
  <h1 @click="countUp">{{ count }}</h1>
</template>

ref関数

糖衣構文の場合

<script setup>
import { ref } from 'vue'

const count = ref(0)
const msg = ref('hello')
const handleClick = () => {
  count.value = 100
  msg.value = 'Bye'
}
</script>
<template>
  <h1 @click="handleClick">{{ count }}: {{ msg }}</h1>
</template>

糖衣構文を使わない場合

<script>
import { ref } from 'vue'
export default ({
  setup() {
    const count = ref(0)
    const msg = ref('hello')
    const handleClick = () => {
      count.value++
    }
    return { count, msg, handleClick }
  }
})
</script>
<template>
  <h1 @click="handleClick">{{ count }}: {{ msg }}</h1>
</template>

reactive関数

糖衣構文の場合

<script setup>
import { reactive } from 'vue'

const obj = reactive({num: 0})
const countUp = () => {
  obj.num++
}
</script>
<template>
  <input type="number" v-model.number="obj.num">
  <button type="button" @click="countUp">countUp</button>
</template>

糖衣構文を使わない場合

<script>
import { reactive } from 'vue'

export default ({
  setup() {
    const obj = reactive({num: 0})
    const countUp = () => {
      obj.num++
    }
    return {
      obj,
      countUp
    }
  }
})
</script>
<template>
  <input type="number" v-model.number="obj.num">
  <button type="button" @click="countUp">countUp</button>
</template>
モバイルバージョンを終了