點燈坊

失くすものさえない今が強くなるチャンスよ

使用 calculated 建立 Computed

Sam Xiao's Avatar 2021-08-23

Vue 3 希望我們使用 computed 建立 Computed,但這種方式不方便 Point-free,Vue3-fp 提供了 Curry Function 版本的 calculated

Version

Vue 3.2.0
Vue3-fp 0.3.2

Composition API

calculated000

2 為 state,而 3 為 computed,state 會不斷遞增,而 computed 會永遠比 state 多加 1

<template>
  {{ count }} {{ plus }}
</template>

<script setup>
let count = $ref (0)
let plus = $computed (_ => count + 1)

setInterval (_ => count++, 1000)
</script>

第 6 行

let count = $ref (0)

定義 count state 並設定其初始值為 0

第 7 行

let plus = $computed (_ => count + 1)

Computed 本質為 function,先由 arrow function 建立,再由 $computed 轉為 computed。

Point-free

calculated000

功能不變,但使用 Point-free 改寫。

<template>
  {{ count }} {{ plus }}
</template>

<script setup>
import { ref, computed } from 'vue'
import { read, write } from 'vue3-fp'
import { pipe, inc, always as K } from 'ramda'
import { interval } from 'wink-fp'

let calculated = (...f) => _ => computed (pipe (...f))

let count = ref (0)

let plus = calculated (
  read (count),
  inc
) ()

let incCount = pipe (
  read (count),
  inc,
  write (count)
)

pipe (
  K (incCount),
  interval (1000),
) ()
</script>

15 行

let plus = calculated (
  read (count),
  inc
) ()

使用 calculated 組合出 plus computed:

  • read (count):讀取 count state
  • inc:對值遞增

11 行

let calculated = (...f) => _ => computed (pipe (...f))

calculated 底層仍是 computed,我們只需傳入 function 即可,內部會幫我們 pipe 組合。

Vue3-fp

calculated000

功能不變,但使用 Vue3-fp 改寫。

<template>
  {{ count }} {{ plus }}
</template>

<script setup>
import { ref } from 'vue'
import { read, write, calculated } from 'vue3-fp'
import { pipe, inc, always as K } from 'ramda'
import { interval } from 'wink-fp'

let count = ref (0)

let plus = calculated (
  read (count),
  inc
) ()

let incCount = pipe (
  read (count),
  inc,
  write (count)
)

pipe (
  K (incCount),
  interval (1000),
) ()
</script>

第 7 行

import { read, write, calculated } from 'vue3-fp'

Vue3-fp 已經內建 calculated 可直接使用。

calculated :: (...Function) -> Computed
組合 function 成為 computed

(...Function):可傳入個數不限的 function

Computed:回傳為 computed

Conclusion

  • computed 不方便 Point-free,使用 calculated 才適合 Point-free