This package is a thin wrapper around Vue's shallowRef()
function that exposes the same API as:
- Solid's
createSignal()
: - Angular's proposed
signal()
andcomputed()
:
Technically speaking, Vue refs are already reactive signals. That's why it's easy to replicate the specific API design choices of other frameworks. For more details on the distinction between signals and refs, see the Vue docs on their connection.
To install the package, run:
pnpm install vue-signals # or npm or yarn
Import the createSignal()
function from vue-signals/solid
:
<script lang="ts" setup>
import { createSignal } from 'vue-signals/solid'
const [count, setCount] = createSignal(0)
</script>
<template>
<p>Count: {{ count() }}</p>
<button @click="setCount((v) => v + 1)">
increment
</button>
</template>
Import the signal()
and computed()
functions from vue-signals/angular
:
<script lang="ts" setup>
import { computed, signal } from 'vue-signals/angular'
const count = signal(0)
const double = computed(() => count() * 2)
</script>
<template>
<p>Count: {{ count() }}</p>
<p>Double: {{ double() }}</p>
<button @click="count.update(v => v + 1)">
increment
</button>
<button @click="count.set(0)">
reset
</button>
</template>
type SignalGetter<T> = () => T
type SignalSetter<T> = (v: T | ((v: T) => T)) => void
type Signal<T = any> = [
SignalGetter<T>,
SignalSetter<T>
]
declare function createSignal<T = any>(
value: T,
{ equals }?: { equals?: false | ((prev: T, next: T) => boolean) }
): Signal<T>
type Signal<T = any> = () => T & {
set: (value: T) => void
update: (updater: (value: T) => T) => void
mutate: (mutator: (value: T) => void) => void
}
declare function signal<T = any>(initialValue: T): Signal
declare function computed<T>(getter: (...args: any[]) => T): () => T
Some users may prefer more explicit control over their reactive state (read/write access). For example no other code could trigger changes unless they have access to the setter.
Users new to Vue.js may be confused by the ref()
API. It's not immediately obvious that ref()
returns a reactive and mutable object. This is especially true for users coming from React, where useState()
returns a tuple of [value, setter]
.
- Evan You for his inspirational Solid signal implementations, first appearing in a Tweet and later his Angular implementation.
MIT License © 2023 Johann Schopplich