Skip to content
This repository has been archived by the owner on Jul 10, 2024. It is now read-only.

johannschopplich/vue-signals

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

19 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

📶 vue-signals

NPM version

This package is a thin wrapper around Vue's shallowRef() function that exposes the same API as:

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.

Installation

To install the package, run:

pnpm install vue-signals # or npm or yarn

Usage

Solid

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>

Angular

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>

API

Solid-Style createSignal<T>

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>

Angular-Style 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

FAQ

Why, Though?

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].

Credits

License

MIT License © 2023 Johann Schopplich

MIT License © 2023 Evan You