Skip to content

Setup store - A more comprehensive example #978

Closed
@jenstornell

Description

@jenstornell

I think that the setup way of building a store will be the future. I would love to shift towards that in the docs.

Currently in the docs

https://pinia.vuejs.org/introduction.html#basic-example

export const useCounterStore = defineStore('counter', () => {
  const count = ref(0)
  function increment() {
    count.value++
  }

  return { count, increment }
})

Comprehensive example

import { ref, computed } from 'vue'
import { defineStore } from 'pinia'

export const useStoreCounter = defineStore('counter', () => {
  // STATES
  const count = ref(0)

  // GETTERS
  const isEven = computed(() => {
    return count.value % 2 === 0
  })

  const messageIfEven = computed(() => {
    return (message) => {
      if (!isEven.value) return
      return message
    }
  })

  // ACTIONS
  function increment() {
    count.value++
  }

  return { count, isEven, messageIfEven, increment }
})

Notes

  • I think not everyone will remember the syntax for the imports so I added them.
  • I also added comments to make it really clear what is states, getters and actions.
  • isEven is a getter without arguments which works similar to a value.
  • messageIfEven(message) which works more like a method. It takes an argument and also uses the other getter isEven.
  • In the future we can get rid of .value after values and computed properties by using $ref(), but now we still has to deal with ref().

I hope this can help someone.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions