YouTip LogoYouTip

Vue3 Blog Pinia Favorites

```html\\n\\n\\n\\n \\n \\n Pinia β€” Global State Management | Online Tutorial\\n\\n\\n

Pinia β€” Global State Management | Tutorial

\\n\\n

In this chapter, you will learn how to use Pinia to manage shared data across components and pages, and implement the "Favorite Articles" feature.

\\n\\n
\\n\\n

Why Do We Need Global State Management?

\\n\\n

So far, data has been passed between components using props and emit.

\\n\\n

This works well for simple parent-child relationships, but becomes cumbersome in the following scenarios:

\\n\\n
    \\n
  • Favorite status needs to be synchronized between the homepage and the article detail page.
  • \\n
  • User login status needs to be shared across all pages.
  • \\n
  • Shopping cart data needs to be passed between the navigation bar, product page, and checkout page.
  • \\n
\\n\\n

The pain point of passing props layer by layer: If data from component A needs to reach component D, it must go through B and C as intermediaries, even though these intermediate components don't actually need the data themselves.

\\n\\n

Pinia is the official state management library recommended by Vue3. It provides a global "data center" where any component can directly read and modify data without having to pass propsPassing Down Layer by Layer (layer by layer).

\\n\\n
\\n\\n

Installing and Registering Pinia

\\n\\n

If you selected Pinia when creating the project, you can skip the installation step.

\\n\\n

Otherwise:

\\n\\n
$ npm install pinia
\\n\\n

Register in `main.js`:

\\n\\n

Example

\\n\\n
// File path: src/main.js\\n\\nimport { createApp } from 'vue'\\nimport { createPinia } from 'pinia'\\nimport App from './App.vue'\\nimport router from './router'\\n\\nconst app = createApp(App)\\n\\n// Create a Pinia instance and register it\\nconst pinia = createPinia()\\napp.use(pinia)\\napp.use(router)\\napp.mount('#app')
\\n\\n
\\n\\n

defineStore β€” Defining a Store

\\n\\n

The core of Pinia is the Store (Store), which manages a piece of independent state.

\\n\\n

A Store consists of three parts:

\\n\\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n
PartFunctionAnalogy
stateStores dataComponent's data / ref
gettersDerives computed dataComponent's computed
actionsMethods to modify dataComponent's methods / function
\\n\\n

Example

\\n\\n
// File path: src/stores/useFavoriteStore.js\\n\\nimport { defineStore } from 'pinia'\\nimport { ref, computed } from 'vue'\\n\\nexport const useFavoriteStore = defineStore('favorite', () => {\\n  // ====== state: Define state using ref ======\\n  const favoriteIds = ref([])\\n\\n  // Restore favorites from localStorage\\n  const saved = localStorage.getItem('blog-favorites')\\n  if (saved) {\\n    favoriteIds.value = JSON.parse(saved)\\n  }\\n\\n  // ====== getters: Define computed properties ======\\n  const favoriteCount = computed(() => favoriteIds.value.length)\\n\\n  function isFavorite(articleId) {\\n    return favoriteIds.value.includes(articleId)\\n  }\\n\\n  // ====== actions: Define modification methods using regular functions ======\\n  function toggleFavorite(articleId) {\\n    const index = favoriteIds.value.indexOf(articleId)\\n    if (index === -1) {\\n      favoriteIds.value.push(articleId) // Add to favorites\\n    } else {\\n      favoriteIds.value.splice(index, 1) // Remove from favorites\\n    }\\n\\n    // Sync to localStorage (persistent storage)\\n    localStorage.setItem('blog-favorites', JSON.stringify(favoriteIds.value))\\n  }\\n\\n  return { favoriteIds, favoriteCount, isFavorite, toggleFavorite }\\n})
\\n\\n

> The second parameter of `defineStore` can be written in two ways: Options Store (similar to Vue2's data/methods/computed object syntax) and Setup Store (using the composition API function syntax). It is recommended to use Setup Store, which is completely consistent with the ` \\n\\n```

← Skills TestingSkills Dependencies β†’