DEV Community

cn-2k
cn-2k

Posted on

9 1

Creating stores with pinia in Vue 3 + Typescript

Pinia is the new state management system for Vue and in this article I'll show two ways of use this amazing tool with Typescript and simple examples.

1 - Simple store with Typescript assertion

import { defineStore } from "pinia";
import type { MyInterface } from "@/types";

type RootState = {
  myState: MyInterface[];
};

const useMyStore = defineStore("franchiseStore", {
  state: () =>
    ({
      myState: [],
    } as RootState),
  actions: {
    setCurrentState(state: MyInterface[]) {
      this.myState = state
    },
  },
});

export default useMyStore;
Enter fullscreen mode Exit fullscreen mode

2 - Simple store with Typescript assertion and using Composition API

import { defineStore } from 'pinia';
import { ref } from 'vue';
import type { MyInterface } from '@/types'

export const useMyStore = defineStore('myStore', () => {

  const myState = ref<Array<MyInterface>>([]);

  function setCurrentState(state: MyInterface[]) {
    myState.value = state
  }

  return { myState, setCurrentState };
});

export default useMyStore;
Enter fullscreen mode Exit fullscreen mode

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs