Skip to content

Instantly share code, notes, and snippets.

@Zikoat
Last active January 19, 2024 10:11
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Zikoat/ec47ff3646f889d09f8c6d350e6060f6 to your computer and use it in GitHub Desktop.
Save Zikoat/ec47ff3646f889d09f8c6d350e6060f6 to your computer and use it in GitHub Desktop.
vue2-zustand

How to use Zustand with Vue 2

💻 Check out this Codesandbox demo: Vue 2 Playground

ℹ️ This approach works for Vue 2.6 and above.

🔍 Tiny: Just 10 lines of source code, no dependencies.

✨ The same Zustand store can be used with different libraries, such as Vue, React, or Svelte.

Installation

  1. Copy vueZustand.ts to your project.

Getting Started

  1. Create a vanilla Zustand store, like in bearStore.ts.
  2. Create your Vue store by passing the created vanilla Zustand store to createFromStore, as done in bearStore.ts

Usage

  1. In the Vue component where you want to use the store, import the Vue store and use it. See BearPopulation.vue

The Vue store you have created is reactive, and when the state in Zustand updates, your component will update accordingly.

Vue's observable will only react to changes in the parts of your store that actually change, so there is no need to slice and check for equality as this is handled by Vue's observable. For more information, visit the Vue observable documentation.

<template>
<div>
Bear population: {{ bearStore.bears }}
<br />
<button @click="() => bearStore.increasePopulation()">
Increase population
</button>
</div>
</template>
<script>
import { bearStoreVue } from "./bearStore";
export default {
name: "BearPopulation",
data() {
return {
bearStore: bearStoreVue,
};
},
};
</script>
import { createStore } from "zustand/vanilla";
import { createFromStore } from "./vueZustand";
type BearState = {
bears: number;
increasePopulation: () => void;
};
const bearStoreVanilla = createStore<BearState>((set) => ({
bears: 0,
increasePopulation: () => set((state) => ({ bears: state.bears + 1 }))
}));
export const bearStoreVue = createFromStore(bearStoreVanilla);
import Vue from "vue";
import { StoreApi } from "zustand/vanilla";
export const createFromStore = <T extends object>(store: StoreApi<T>) => {
const state = store.getState();
const observable = Vue.observable(state);
store.subscribe((newState) => {
Object.assign(observable, newState);
});
return observable;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment