1.安装

yarn add pinia

2.注册,修改main.js

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

3.使用

新建store文件夹,新建helloworld.js文件,内容如下

import { defineStore } from 'pinia'

// 第一个参数是应用程序中 store 的唯一 id
export const demoStore = defineStore('demo', {
    state: () => {
        return {
            count: 100
        }
    },
    getters: {},
    actions: {},
})

4.HelloWorld.vue中使用

<script setup>
import { ref, reactive } from 'vue'
import { storeToRefs } from 'pinia'
import { demoStore } from '../store/helloworld'

defineProps({
  msg: String
})

const store = demoStore()

//解构
const { count } = storeToRefs(store)

// 直接count++是无法存储到pinia中的。应该通过store.$patch()修改pinia中的值【推荐】,或者使用actions修改pipia中的值,或者store.count++。
function plus() {
  store.$patch({
    count: store.count + 1
  })
}
</script>

<template>
  <h1>{{ msg }}</h1>

  <p>
    Recommended IDE setup:
    <a href="https://code.visualstudio.com/" target="_blank">VS Code</a>
    +
    <a href="https://github.com/johnsoncodehk/volar" target="_blank">Volar</a>
  </p>

  <p>
    <a href="https://vitejs.dev/guide/features.html" target="_blank">
      Vite Documentation
    </a>
    |
    <a href="https://v3.vuejs.org/" target="_blank">Vue 3 Documentation</a>
  </p>

  <button type="button" @click="plus()">count is: {{ count }}</button>
  <p>
    Edit
    <code>components/HelloWorld.vue</code> to test hot module replacement.
  </p>
</template>

<style scoped>
a {
  color: #42b983;
}
</style>

5.持久化插件(注意!注意!注意!:只有真正的改变了store的值,才能触发持久化的存储,博主学习的时候在这里踩了很久的坑,当时只是改变了数据的引用,并没有真正改变pipia里面的值,以为pinia-plugin-persist失效了,看了源码才知道原理是通过$subscribe监听,断点调试发现没有触发才恍然大悟

Getting started | Pinia Plugin PersistPersist pinia state data in sessionStorage or other storages.https://seb-l.github.io/pinia-plugin-persist/#install终端安装

yarn add pinia-plugin-persist

main.js注册 

import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import { createPinia } from 'pinia'
import piniaPersist from 'pinia-plugin-persist'

const pinia = createPinia()
pinia.use(piniaPersist)

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

使用:修改store文件夹下的helloworld.js,内容如下:

import { defineStore } from 'pinia'

// 第一个参数是应用程序中 store 的唯一 id
export const demoStore = defineStore('demo', {
    state: () => {
        return {
            count: 100
        }
    },
    getters: {
        //state与getters中的Key不能冲突,否则会读取失败
        getCount:(state)=>state.count
    },
    actions: {
        plus(){
            this.count++
        }
    },
    persist: {
        enabled: true,
    }
})