Vue3 之pinia状态管理

一、文档

https://pinia.vuejs.org/zh/introduction.html

二、数据持久化

安装插件

npm install pinia-plugin-persistedstate

配置

// main.js
import { createApp } from 'vue'
import App from './App.vue'

import { createPinia } from 'pinia'
import piniaPluginPersistedstate from 'pinia-plugin-persistedstate'

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

const app = createApp(App)
app.use(pinia)
app.mount('#app')

使用

// stores/user.ts
import { defineStore } from 'pinia'

export const useUserStore = defineStore('user', {
  state: () => ({
    token: '',
    username: ''
  }),
  persist: true
})

详细配置

persist: {
  key: 'user', // 自定义存储 key
  storage: sessionStorage, // 使用 sessionStorage
  paths: ['token'] // 仅持久化 token
}

三、简单使用

main.js

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

store

import {defineStore} from 'pinia'
const useCountStore = defineStore('counter', {
    state: ()=>{
        return {
            count: 0
        }
    },
    getters: {
        getCount(state){
            return state.count
        }
    },
    actions: {
        add(){
            this.count++
        }
    }
})

export default useCountStore

vue

<script setup>
import { ref, computed } from 'vue'
import useCountStore from '../store';
import { storeToRefs } from 'pinia';

const store = useCountStore()
const msg = ref('vue')

// const count = computed(() => {
//   return store.count
// })

const { count } = storeToRefs(store)

const add = () => {
  store.add()
  console.log(store.getCount)
}
</script>

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

  <div class="card">
    <button type="button" @click="add()">count is {{ count }}</button>
  </div>
</template>

<style scoped></style>

 

posted @ 2025-10-12 21:39  样子2018  阅读(12)  评论(0)    收藏  举报