VUE3使用Pinia

108 阅读1分钟

Pinia 是 Vue 的存储库,它允许您跨组件/页面共享状态,类似 Vuex,是 Vue 的另一种状态管理方案!而Pinia 是为 Vue 3 设计的状态管理库, Vuex 是为 Vue 2 设计的。
如果使用 Vue 3,并且需要更好的 TypeScript 支持和性能优化,那么个人比较推荐 Pinia 。如果使用 Vue 2 或已经有大量的 Vuex 代码和插件,那么个人比较推荐 Vuex

安装Pinia

yarn add pinia
# 或者使用 npm
npm install pinia

在main.ts引入pinia

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

import { createPinia } from 'pinia'

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

创建 Pinia Store 文件

// src/stores/index.ts
export const useIndexStore = defineStore('indexStore', {
    state: () => ({
        name: 'Erick',
    }),
    getters: {
        getName: (state) => {
            return state.name
        },
    },
    actions: {
        updateName(newName) {
            this.name = newName
        },
    },
})

在组件中使用 store

<template>
    <div>{{ indexStore.name }}</div>
    <div>{{ name }}</div>
    <button @click="indexStore.updateName('Erick027')">Change Name</button>
</template>
<script setup lang="ts">
import { computed } from 'vue';
import { useIndexStore } from '@/stores/index'

const indexStore = useIndexStore()
// 使用变量接收
const name = computed(() => indexStore.getName)
</script>

Pinia 持久化插件 pinia-plugin-persistedstate 安装、使用

安装pinia-plugin-persistedstate

yarn add pinia-plugin-persist
# 或者使用 npm
npm install pinia-plugin-persist

在pinia引入使用pinia-plugin-persist

// src/main.ts
import { createApp } from 'vue'
import App from './App.vue'

import { createPinia } from 'pinia'
import piniaPluginPersist from "pinia-plugin-persist";

const pinia = createPinia().use(piniaPluginPersist);

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

在Pinia Store 文件中使用

// src/stores/index.ts
export const useIndexStore = defineStore('indexStore', {
    state: () => ({
        name: '',
    }),
    getters: {
        getName: (state) => {
            return state.name
        },
    },
    actions: {
        updateName(newName) {
            this.name = newName
        },
    },
    // 开启本地数据缓存
    persist: {
        enabled: true,
        // strategies: [
        //     {
        //         key: "name",  // 存储的KEY
        //         storage: localStorage, // 存储空间,默认存储到 sessionStorage 里面
        //         paths: ['name'] // 存储数据,默认存储state里面的所有数据
        //     }
        // ]
    }
})

实例

// src/stores/index.ts
export const useIndexStore = defineStore('indexStore', {
    state: () => ({
        name: 'Erick',
    }),
    getters: {
        getName: (state) => {
            return state.name
        },
    },
    actions: {
        updateName(newName: string) {
            this.name = newName
        },
    },
    // 开启本地数据缓存
    persist: {
        enabled: true,
        strategies: [
            {
                key: "name",  // 存储的KEY
                storage: localStorage, // 存储空间,默认存储到 sessionStorage 里面
                paths: ['name'] // 存储数据,默认存储state里面的所有数据
            }
        ]
    }
})

image.png