본문 바로가기
Programming/Vue

Pinia - Vue3 State Management

by sayshare 2023. 7. 24.
반응형

What is Pinia?

Pinia is an officially recommended state management package for Vue3. Managing the state of an application is a very challenging task as a developer when the project feature gradually increases. With state management libraries such as Pinia or Vuex, we can reduce lots of boilerplate code and just focus on the functionality of the project instead.

Implementation

In projectdirectory, install the following package:

 

yarn:  

yarn add pinia

or npm: 

npm install pinia

In the main.js

import {createApp} from             'vue'            
import App from             './App.vue'            
import {createPinia} from             'pinia' ;

createApp(App)
	.use(router)
	.use(createPinia())
	.mount( '#app' )

 

Folder structure:

- src
   - stores
      - count.store.js
  - App.vue
  - main.js

 

In src directory , create a folder named stores. Then create a file name count.store.js in the stores directory with the following code:

import {defineStore} from         "pinia" ;

export         const useAuthStore = defineStore({
            id : 'auth' ,
            state : () => ({
                count : 0
    }),
    actions : {
        increase() {
            this .count++
        },
        decrease() {
            this .count--
        }
    }
})

 

In the app. vue file, add the following code:

<script setup>
    import {useCountStore} from     "@/stores/count.store.js" ;
const counter = useCountStore()
< /script>

<template>
  <div>
    <p>{{counter.count}}</ p>
          < button @ click = "counter.increase()" > ADD </ button >      
    < button @ click = "counter.decrease()" > MINUS </ button >      
  </ div >      
</ template >

 

반응형

'Programming > Vue' 카테고리의 다른 글

Vue-Router [Vue Js]  (0) 2023.07.23