DEV Community

Jingtian Zhang
Jingtian Zhang

Posted on

Pinia to replace VueX as Vue Store

Pro

  • supports both vue2 and 3
  • abandon Mutation, only state, getter and action, simplify state management
  • no more nested structure, fits composition api style better
  • supports TypeScript
  • better code splitting

Basic Usage

here lets create a project using vite:

npm init vite@latest
Enter fullscreen mode Exit fullscreen mode

install pinia

npm i pinia
Enter fullscreen mode Exit fullscreen mode

the entry main.ts file would be:

image.png

and then you can create a store

image.png

and use it

image.png

when you need to use multiple properties from store, to make it easier, we can destrcuture them using Pinia's storeToRefs

image.png

Pinia State Management

simple data modification can be done using store.propertyName directly

image.png

if the modification involves much data, we can use $patch, as instructed in its doc, it will improve speed of modification

$patch accepts two args:

  • $patch + object
  • $patch + function

image.png

you can also make change via action

  • add chagneState method in store.actions

image.png

  • call store.methodName directly

image.png

Getters inside Pinia

the getter inside pinia is almost the same to the one in vue

getter‘s value can be cached, so even if no value change, it will only be called once for multiple calls

  • add getter method

image.png

  • use it inside component

image.png

inside getter we can also use this to modify data

image.png

call one store in another

let's create a new store file called substore.ts

image.png

and use it in index.ts

image.png

Conclusion

well, it is the default recommended by Vue team to replace Vuex, and you can use it in production already.

Top comments (0)