まとめてリアクティブにするreactive()

date
Mar 1, 2023
repo_url
slug
reactive
status
Published
summary
type
Post
thumbnail_url
tags
vue
outer_link
リアクティブ変数はref() で用意できるが、複数のデータをひとつのオブジェクトとしてリアクティブにしたい場合はreactive() 関数が使える。
基本的にはref()を使用して、どうしてもオブジェクトとしてまとめる必要がある場合はreactive()を使う、というスタンスがベター。
<script setup lang="ts">
import {reactive, computed} from "vue"; //reactiveはimportが必要

// 以下、円の面積を求める処理
const data = reactive({
	PI: 3.14,
	radius: Math.round(Math.random() * 10)
});

// 円の面積の算出プロパティ
const area = computed(
	(): number => {
		return data.radius * data.radius * data.PI;
	}
);
// 半径の変数に新しい乱数を1秒ごとに格納
setInterval(
	():void => {
		data.radius = Math.round(Math.random() * 10);
	},
	1000
);
</script>

<template>
	<p>半径{{data.radius}}メートルの円の面積を円周率{{data.PI}}で計算すると、結果は{{area}}平方メートル</p>
</template>

© Hayato Kamiyama 2023 - 2024 - Build with Next.js & Notion