Search icon
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
Frontend Development Projects with Vue.js 3 - Second Edition

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

Product type Book
Published in Mar 2023
Publisher Packt
ISBN-13 9781803234991
Pages 628 pages
Edition 2nd Edition
Languages
Authors (4):
Maya Shavin Maya Shavin
Profile icon Maya Shavin
Raymond Camden Raymond Camden
Profile icon Raymond Camden
Clifford Gurney Clifford Gurney
Profile icon Clifford Gurney
Hugo Di Francesco Hugo Di Francesco
Profile icon Hugo Di Francesco
View More author details

Table of Contents (20) Chapters

Preface 1. Part 1: Introduction and Crash Course
2. Chapter 1: Starting Your First Vue Project 3. Chapter 2: Working with Data 4. Chapter 3: Vite and Vue Devtools 5. Part 2: Building Your First Vue App
6. Chapter 4: Nesting Components (Modularity) 7. Chapter 5: The Composition API 8. Chapter 6: Global Component Composition 9. Chapter 7: Routing 10. Chapter 8: Animations and Transitions 11. Part 3: Global State Management
12. Chapter 9: The State of Vue State Management 13. Chapter 10: State Management with Pinia 14. Part 4: Testing and Application Deployment
15. Chapter 11: Unit Testing 16. Chapter 12: End-to-End Testing 17. Chapter 13: Deploying Your Code to the Web 18. Index 19. Other Books You May Enjoy

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 2023 Publisher: Packt ISBN-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.
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}