Reader small image

You're reading from  Frontend Development Projects with Vue.js 3 - Second Edition

Product typeBook
Published inMar 2023
Reading LevelIntermediate
PublisherPackt
ISBN-139781803234991
Edition2nd Edition
Languages
Tools
Right arrow
Authors (4):
Maya Shavin
Maya Shavin
author image
Maya Shavin

Maya is Senior Software Engineer in Microsoft, working extensively with JavaScript and frontend frameworks and based in Israel. She holds a B.Sc in Computer Sciences, B.A in Business Management, and an International MBA from University of Bar-Ilan, Israel. She has worked with JavaScript and latest frontend frameworks such as React, Vue.js, etc to create scalable and performant front-end solutions at companies such as Cooladata and Cloudinary, and currently Microsoft. She founded and is currently the organizer of the VueJS Israel Meetup Community, helping to create a strong playground for Vue.js lovers and like-minded developers. Maya is also a published author, international speaker and an open-source library maintainer of frontend and web projects.
Read more about Maya Shavin

Raymond Camden
Raymond Camden
author image
Raymond Camden

Raymond Camden is a developer advocate for IBM. His work focuses on the MobileFirst platform, Bluemix, hybrid mobile development, Node.js, HTML5, and web standards in general. He is a published author and presents at conferences and user groups on a variety of topics. Raymond can be reached at his blog, on Twitter, or via email. He is the author of many development books, including Apache Cordova in Action and Client-Side Data Storage.
Read more about Raymond Camden

Clifford Gurney
Clifford Gurney
author image
Clifford Gurney

Clifford Gurney is a solution-focused and results-oriented technical lead at a series-A funded startup. A background in communication design and broad exposure to leading digital transformation initiatives enriches his delivery of conceptually designed front-end solutions using Vue JS. Cliff has presented at the Vue JS Melbourne meetups and collaborates with other like-minded individuals to deliver best in class digital experience platforms.
Read more about Clifford Gurney

Hugo Di Francesco
Hugo Di Francesco
author image
Hugo Di Francesco

Hugo Di Francesco is a software engineer who has worked extensively with JavaScript. He holds a MEng degree in mathematical computation from University College London (UCL). He has used JavaScript across the stack to create scalable and performant platforms at companies such as Canon and Elsevier and in industries such as print on demand and mindfulness. He is currently tackling problems in the travel industry at Eurostar with Node.js, TypeScript, React, and Kubernetes while running the eponymous Code with Hugo website. Outside of work, he is an international fencer, in the pursuit of which he trains and competes across the globe.
Read more about Hugo Di Francesco

View More author details
Right arrow

State Management with Pinia

In the previous chapter, you were introduced to the idea of a state and how it can be used to synchronize data between multiple components in a Vue application. You first saw an example of handling states via event broadcasting and then improved upon that by including a simple state library.

In this chapter, you’ll learn about the Pinia project and understand how it can help manage complex state interactions in your Vue applications. You’ll learn how to install the library and start using it right away.

In this chapter, we will cover the following topics:

  • What Pinia is
  • Installing Pinia
  • Using Pinia to create a store
  • Adding and using getters in your Pinia store
  • Working with Pinia actions
  • Debugging Pinia in Devtools

Technical requirements

There are no technical requirements for this chapter outside of the git CLI that you will have already used by now. You can find this chapter’s source here: https://github.com/PacktPublishing/Frontend-Development-Projects-with-Vue.js-3/tree/v2-edition/Chapter10

What Pinia is

Pinia (https://pinia.vuejs.org) is a state management library for Vue.js applications. As you saw in Chapter 9, The State of Vue State Management, handling data that must be synchronized between multiple different components requires some form of management. Pinia helps with this by providing a simple method of setting up a central store that contains your application’s state. Your components make use of this store to ensure they’re all using the same information.

Pinia began as an experiment for Vue 3 but evolved to support Vue 2 as well. Pinia is now the recommended state management library for Vue applications, with the venerable Vuex (https://vuex.vuejs.org/) now in maintenance mode:

Figure 10.1 – The Pinia website

Figure 10.1 – The Pinia website

Along with state management, using Pinia also provides other benefits, including the following:

  • Devtools support via the Vue extension. This extension supports Chrome, Edge, and Firefox. There...

Installing Pinia

To use Pinia in a Vue application, you’ve got two ways to add it. First, when creating a new Vue application via the standard method (npm init vue@latest), one of the questions asked will be whether you wish to include Pinia. Simply say Yes here:

Figure 10.2 – Indicating whether you wish to add Pinia to a new Vue project

Figure 10.2 – Indicating whether you wish to add Pinia to a new Vue project

If you have an existing Vue 3 application, adding support is nearly as easy. First, in the project, add Pinia via npm: npm install pinia. Next, you need to include Pinia in the application. Your main.js file (located in the /src directory) will look like so:

import { createApp } from 'vue'
import App from './App.vue'
createApp(App).mount('#app')

Begin by importing Pinia:

import { createApp } from 'vue'
import { createPinia } from 'pinia'
import App from './App.vue'
createApp(App).mount('#app')

Then, modify the createApp line...

Using Pinia to create a store

Let’s start using Pinia by demonstrating how to define a store within it and then use the state data in an application:

  1. Create a new Vue application and enable Pinia, as shown in Figure 10.2. This will give you a Vue application with a store already created. You will find it under src/stores/counter.js:
    import { defineStore } from 'pinia'
    export const useCounterStore = defineStore({
      id: 'counter',
      state: () => ({
        counter: 1
      }),
      getters: {
        doubleCount: (state) => state.counter * 2
      },
      actions: {
        increment() {
          this.counter++
        }
      }
    })

This simple Pinia file demonstrates all three of the major aspects we defined previously – the state, getters, and actions. In this section, we’re only concerned...

Adding and using getters in your Pinia store

As stated earlier, getters in Pinia act just like computed properties. They allow you to request a simple value that’s generated by custom logic written in a function.

If you go back to the original Pinia store created by default, you’ll see it had a getter defined:

import { defineStore } from 'pinia'
export const useCounterStore = defineStore({
  id: 'counter',
  state: () => ({
    counter: 0
  }),
  getters: {
    doubleCount: (state) => state.counter * 2
  },
  // rest of file...
})

The doubleCount getter simply takes the current value of counter and returns the double of it. As demonstrated, getters are automatically passed the current state as an argument, which can then be used in whatever logic makes sense in your particular getter function.

Just like regular values defined in the...

Working with Pinia actions

Actions are the Pinia equivalent of component methods. They let you define custom logic for a store and can be asynchronous as well. This is useful for times when server-side logic needs to be called to validate a change to the state. Actions are defined with the actions block of a Pinia object, and you can see an example in the default store created by Pinia:

import { defineStore } from 'pinia'
export const useCounterStore = defineStore({
  id: 'counter',
  state: () => ({
    counter: 0
  }),
  // rest of store...
  actions: {
    increment() {
      this.counter++
    }
  }
})

In this example, the increment action simply takes the counter value and adds one to it. Actions access state values by using the this scope and, as stated previously, can be asynchronous as well. An example...

Debugging Pinia in Devtools

Earlier in Chapter 3, Vite and Vue Devtools, you were introduced to Vue Devtools. Devtools are an incredibly powerful way to debug and optimize web applications, and the Vue plugin makes them even more vital for Vue developers. What makes Vue Devtools even more powerful is automatic recognition and support for applications using Pinia.

Let’s take a quick tour of what this support looks like by using the Color Preview application last modified in Exercise 10.03. Run the application from the command line, open the URL in your browser, and open your developer tools. Note the Pinia tab on the right in Figure 10.9:

Figure 10.9 – Pinia support in Vue Devtools

Figure 10.9 – Pinia support in Vue Devtools

Right away, you can see you’ve got access to the complete state as well as any getters. If you start modifying the RGB values, you can see them immediately reflected:

Figure 10.10 – The state values update as the user works with the app

Figure 10.10 – The state values update as the user...

Summary

This chapter introduced you to Pinia, Vue’s recommended library for handling a shared state in a complex, multi-component application.

We began by discussing how to install Pinia. Next, we introduced states and showed you how to use those values in your components.

You looked at getters as a way of handling virtual properties and encapsulating logic.

Finally, you saw how actions let you define custom methods for working with your state.

In the next chapter, you’ll be introduced to testing with Vue, specifically unit testing, which will prepare you for end-to-end testing in the chapter after that.

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Frontend Development Projects with Vue.js 3 - Second Edition
Published in: Mar 2023Publisher: PacktISBN-13: 9781803234991
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €14.99/month. Cancel anytime

Authors (4)

author image
Maya Shavin

Maya is Senior Software Engineer in Microsoft, working extensively with JavaScript and frontend frameworks and based in Israel. She holds a B.Sc in Computer Sciences, B.A in Business Management, and an International MBA from University of Bar-Ilan, Israel. She has worked with JavaScript and latest frontend frameworks such as React, Vue.js, etc to create scalable and performant front-end solutions at companies such as Cooladata and Cloudinary, and currently Microsoft. She founded and is currently the organizer of the VueJS Israel Meetup Community, helping to create a strong playground for Vue.js lovers and like-minded developers. Maya is also a published author, international speaker and an open-source library maintainer of frontend and web projects.
Read more about Maya Shavin

author image
Raymond Camden

Raymond Camden is a developer advocate for IBM. His work focuses on the MobileFirst platform, Bluemix, hybrid mobile development, Node.js, HTML5, and web standards in general. He is a published author and presents at conferences and user groups on a variety of topics. Raymond can be reached at his blog, on Twitter, or via email. He is the author of many development books, including Apache Cordova in Action and Client-Side Data Storage.
Read more about Raymond Camden

author image
Clifford Gurney

Clifford Gurney is a solution-focused and results-oriented technical lead at a series-A funded startup. A background in communication design and broad exposure to leading digital transformation initiatives enriches his delivery of conceptually designed front-end solutions using Vue JS. Cliff has presented at the Vue JS Melbourne meetups and collaborates with other like-minded individuals to deliver best in class digital experience platforms.
Read more about Clifford Gurney

author image
Hugo Di Francesco

Hugo Di Francesco is a software engineer who has worked extensively with JavaScript. He holds a MEng degree in mathematical computation from University College London (UCL). He has used JavaScript across the stack to create scalable and performant platforms at companies such as Canon and Elsevier and in industries such as print on demand and mindfulness. He is currently tackling problems in the travel industry at Eurostar with Node.js, TypeScript, React, and Kubernetes while running the eponymous Code with Hugo website. Outside of work, he is an international fencer, in the pursuit of which he trains and competes across the globe.
Read more about Hugo Di Francesco