Component と Composition APIについて

refとreactiveについて

変数をリアクティブな値にするにはrefreactiveを使用する

refの値にアクセスするには.value でアクセスする

TSでrefを使用する際は、ref 関数に対してジェネリクスで型の情報を与える

<script setup lang="ts">
	import { ref } from 'vue';
	const itemName1 = ref<string>('Desk')
	const input = (event: any) => {
	  itemName1.value = event.target.value
	}
</script>
<template>
  <div class="container">
    <h1>最近の支出</h1>
    <input @input="input">
    <div class="payment">
      <label>{{ itemName1 }}</label>
      <label>{{ price1 }}円</label>
      <a :href="url1">bought at...</a>
      <button @click="buy(itemName1)">BUY</button>
    </div>
	</div>
</template>

reactive はオブジェクトをリアクティブな値として扱いたい時に利用する

<script setup lang="ts">
import { ref, reactive } from 'vue';

const item2 = reactive({
  name: 'Bike',
  price: 20000
})
const input = (event: any) => {
  item2.name = event.target.value
}
</script>
<template>
  <div class="container">
    <h1>最近の支出</h1>
    <input @input="input">
    <div class="payment">
      <label>{{ item2.name }}</label>
      <label>{{ item2.price }}円</label>
      <a :href="url1">bought at...</a>
    </div>
	</div>
</template>

refreactiveの使い分けとしては

compotedについて

vue3でcompotedを利用するにはvueからインポートする必要がある

<script setup lang="ts">
import { ref, reactive, computed } from 'vue';
const item2 = reactive({
  name: 'Bike',
  price: 20000
})
const budget = 50000

const priceLabel = computed((): string => item2.price > budget ? 'too expensive' : item2.price + '円')
</script>

toRef

リアクティブオブジェクトのプロパティに対する refを作成するために使用する

リアクティブなオブジェクトのプロパティをリアクティブ性を保ったまま引き渡すことができる

const state = reactive({
  foo: 1,
  bar: 2
})
const fooRef = toRef(state, 'foo')

prop の ref を composition 関数に渡したいときに使える

export default {
  setup(props) {
    useSomeFeature(toRef(props, 'foo'))
  }
}