reactify

reactify

通常の関数をリアクティブな関数に変換します。変換された関数は、引数として ref を受け取り、適切な型付けがされた ComputedRef を返します。

::: tip アプリケーションを見てみたい、または事前にリアクティブ化された関数を探していますか?

⚗️ Vue Chemistry をチェックしてみてください! :::

使用法

基本的な例

import { reactify } from '@vueuse/core'
import { shallowRef } from 'vue'

// 通常の関数
function add(a: number, b: number): number {
  return a + b
}

// これで refs を受け取り、computed ref を返します
// (a: number | Ref<number>, b: number | Ref<number>) => ComputedRef<number>
const reactiveAdd = reactify(add)

const a = shallowRef(1)
const b = shallowRef(2)
const sum = reactiveAdd(a, b)

console.log(sum.value) // 3

a.value = 5

console.log(sum.value) // 7

リアクティブなピタゴラスの定理を実装する例。

import { reactify } from '@vueuse/core'
import { shallowRef } from 'vue'

const pow = reactify(Math.pow)
const sqrt = reactify(Math.sqrt)
const add = reactify((a: number, b: number) => a + b)

const a = shallowRef(3)
const b = shallowRef(4)
const c = sqrt(add(pow(a, 2), pow(b, 2)))
console.log(c.value) // 5

// 5:12:13
a.value = 5
b.value = 12
console.log(c.value) // 13

このようにすることもできます:

import { reactify } from '@vueuse/core'
import { shallowRef } from 'vue'

function pythagorean(a: number, b: number) {
  return Math.sqrt(a ** 2 + b ** 2)
}

const a = shallowRef(3)
const b = shallowRef(4)

const c = reactify(pythagorean)(a, b)
console.log(c.value) // 5

リアクティブな stringify を作成する別の例

import { reactify } from '@vueuse/core'
import { shallowRef } from 'vue'

const stringify = reactify(JSON.stringify)

const obj = shallowRef(42)
const dumped = stringify(obj)

console.log(dumped.value) // '42'

obj.value = { foo: 'bar' }

console.log(dumped.value) // '{"foo":"bar"}'