Skip to content

A quick way to define local component state in Vue 3

Notifications You must be signed in to change notification settings

evrys/vue-define-state

Repository files navigation

vue-define-state latest release

This package exports a defineState function which wraps Vue's reactive, turning all provided get methods into computed properties.

Example

Here's how you would write the Markdown example from the Vue website using defineState instead:

<script setup lang="ts">
import { marked } from 'marked'
import { debounce } from 'lodash-es'
import { defineState } from 'vue-define-state'

const state = defineState({
  input: '# hello',

  get output() {
    return marked(this.input)
  }
})

const update = debounce((e: Event) => {
  state.input = (e.target as HTMLInputElement).value
}, 100)
</script>

<template>
  <div class="editor">
    <textarea class="input" :value="state.input" @input="update"></textarea>
    <div class="output" v-html="state.output"></div>
  </div>
</template>

Why?

If you used vue-class-component extensively in Vue 2, defineState makes it easier to upgrade old code to the Vue 3 composition API.

I personally find this syntax a little more succinct and easier to work with than manually calling ref and computed, especially when working with larger components. It's similar to useLocalObservable from Mobx.

About

A quick way to define local component state in Vue 3

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published