vue3项目搭建连载文章(4)-Pinia状态管理

62 阅读1分钟

Pinia说明

Pinia最初是在 2019 年 11 月左右重新设计使用Composition API的 Vue Store 外观的实验。 从那时起,最初的原则仍然相同,但 Pinia 适用于Vue2和Vue3,并且不需要你使用组合 API。Pinia 是 Vue 的存储库,它允许您跨组件/页面共享状态 Pinia 是一个用于 Vue 的状态管理库,类似 Vuex, 是 Vue 的另一种状态管理方案,Pinia 2 是对应 Vue3 的版本

安装步骤

// 安装
npm i -S pinia

//数据持久化插件
npm i -S pinia-plugin-persist 

package.json

"dependencies": {
    "element-plus": "^2.2.32",
    "pinia": "^2.0.32",
    "pinia-plugin-persist": "^1.0.0",
    "vue": "^3.2.45",
    "vue-router": "^4.1.6"
  },

在src下建立store文件夹,并创建index.ts, i18n.ts文件。内容分别如下; index.ts

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

const store = createPinia()
store.use(piniaPluginPersist)

 
export default store

i18n.ts

import { defineStore } from "pinia"
 
export const langStore = defineStore({
    id: "i18n", // id是唯一的,如果有多个文件,ID不能重复
    state: () => {
        return {
            language: "en"
        }
    },
    actions: {
        setLanguage(data: string) {
            debugger
            console.log("--aa--"+ data)
            this.language = data
        }
    },
    // 开启数据缓存,在 strategies 里自定义 key 值,并将存放位置由 sessionStorage 改为 localStorage
    // 默认所有 state 都会进行缓存,你可以通过 paths 指定要持久化的字段,其他的则不会进行持久化,如:paths: ['language'] 替换key的位置
    persist: {
        enabled: true,
        strategies: [
            {
                key: "language",
                storage: localStorage,
            },
        ],
    },
})

main.js配置

import store from './store'
createApp(App).use(store).use(router).use(ElementPlus,{ locale }).mount('#app')

以上已经完成了安装和配置工作。

使用说明

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

  <div class="card">
    <button type="button" @click="count++">count is {{ count }}</button>
   <button type="button" @click="setCache()">设置缓存</button>
  </div>

</template>

<script setup lang="ts">
import { ref } from 'vue'
import  { langStore }  from "../store/i18n" //此处是引入
const myStore = langStore()

defineProps<{ msg: string }>()

const count = ref(0)

function setCache(){
   console.log("--set cache--");
   myStore.setLanguage("zh"); 
}
</script>

<style scoped>
.read-the-docs {
  color: #888;
}
</style>


效果图片

20230303162225.jpg