Cody Bontecou

Import Pinia Store Into Other Store

September 28, 2022 · 1 minute read · Vue,State,Pinia

Pinia makes state management within Vue apps a breeze to work with.

A common problem I run into is needing to access state from a different store. This can be solved using Pinia's composition syntax rather than the option syntax.

// store/count.js
import { ref } from 'vue'
import { defineStore } from 'pinia'

export const useCountStore = defineStore('count-store', () => {
  const count = ref(0)

  function increaseCount() {
    count = count + 1
  }

  return { count, increaseCount }
})

They can now be imported and used within other Pinia stores like so:

// store/api.js
import { ref } from 'vue'
import { defineStore, storeToRefs } from 'pinia'
import { useCountStore } from './count'

export const useApiStore = defineStore('api-store', () => {
  const countStore = useCountStore()
  const { count } = storeToRefs(countStore)
  const { increaseCount } = countStore

  function displayCount() {
    console.log(count)
  }

  function increment() {
    increaseCount()
  }

  return { displayCount, increment }
})

Newsletter

Subscribe to get my latest content. No spam.