4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Vue 3 setupメソッド

Posted at

Vue3で追加されたsetupメソッド

vue 3で導入されたComposition APIのsetupメソッドを使った時の備忘録

Vue 2.5までの書き方

コンポーネントにdata、methods、computed、createdを区別していた。

Vue.js
<template>
  <div></div>
</template>

<script>
export default {
  data() {

  },
  methods: {

  },
  computed: {

  },
  created() {

  },

}
</script>

<style>

</style>

Vue3の書き方

vue.js
<template>
  <div>ComositionTest</div>
  <div>
    <p>商品名: {{ item.name }}</p>
    <p>単価: {{ item.price }}</p>
    <p>合計: {{ totalPrice }}</p>
  </div>
  <div>数量</div>
  <button @click="decrement">-</button>
  <button @click="increment">+</button>
</template>

setupメソッドではdata、computed、methodsを区別することなく、まとめて書くことができます。

<script>
// import { reactive, computed } from 'vue'
import { reactive } from 'vue'
import useCounter from '@/composables/useCounter'


export default {
  setup() {
    const item = reactive({
      name: '商品名',
      price: '100',
      amount: '0'
    })

    const { increment, decrement, totalPrice} = useCounter(item)
    return {
      item,
      increment,
      decrement,
      totalPrice
    }
  }
}
</script>
4
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?