快速搞懂Pinia及数据持久化存储(详细教程)

本文介绍Pinia状态管理库的安装、配置与使用方法,包括数据定义、组件中使用Store、数据持久化等核心功能,并对比Pinia与Vuex的区别。

一.安装及使用Pinia

1.安装Pinia两种方式都可,根据个人习惯来

npm install pinia
yarn add pinia

2.在main.ts 中引入并挂载到根实例

// src/main.ts
import { createApp } from 'vue'
import App from './App.vue'
import { createPinia } from 'pinia'
// 创建Vue应用实例
// 实例化 Pinia
// 以插件形式挂载Pinia实例
createApp(App).use(createPinia()).mount('#app')

3.src目录下新建store/study/index.js并写入

Store 是用defineStore()定义的,它的第一个参数是一个独一无二的id,也是必须传入的,Pinia 将用它来连接 store 和 devtools。

defineStore()第二个参数可接受两类值:Setup函数或Options对象

state 属性: 用来存储全局的状态的,这里边定义的,就可以是为SPA里全局的状态了。

getters属性:用来监视或者说是计算状态的变化的,有缓存的功能。

actions属性:对state里数据变化的业务逻辑,需求不同,编写逻辑不同。说白了就是修改state全局状态数据的。

第一种Options式写法:

import { defineStore } from 'pinia'
//  `defineStore()` 的返回值命名最好使用 store 的名字,同时以 `use` 开头且以 `Store` 结尾
export const useStudyStore = defineStore('studyId', {
  state: () => {
    return {
      counter: 0,
    }
  },
  getters:{},
  actions:{}
})

在Options式中:Store 的数据(data),getters 是 Store 的计算属性(computed)而actions则是 Store 的方法(methods)。

第二种Setup式写法:

import { defineStore } from 'pinia'
//  `defineStore()` 的返回值命名最好使用 store 的名字,同时以 `use` 开头且以 `Store` 结尾
export const useStudyStore = defineStore('studyId', ()=>{
  const count = ref(0)
  const name = ref('Ghmin')
  const computedTest= computed(() => count.value * 99)
  function int() {
    count.value++
  }
  return { count, name, computedTest, int}

})

在Setup式中:ref()成为state属性,computed()变成getters,function变成actions

4.使用Store

使用上面两种方式其中一种后,便可以在组件中使用Store了。

<script setup>
import { useStudyStore } from '@/stores/study'
const store = useStudyStore();
</script>

二.具体使用及属性与方法

1.定义数据

import { defineStore } from 'pinia'
export const useStudyStore = defineStore('studyId', {
  state: () => {
    return {
      name: 'Ghmin',
      num:0
    }
  },
})

2.组件中使用

<template>
	<div>
		<h1>vue组件</h1>
		{{ name }}
	</div>
</template>

<script setup>
import { useStudyStore } from '@/stores/study'
const store = useStudyStore();
let { name } = store;
</script>

注:pinia可以直接修改state数据,无需像vuex一样通过mutations才可以修改,所以上面的let { name } = store 这种解构是不推荐的,因为它破坏了响应性。

而为了从 Store 中提取属性,同时保持其响应性,这里需要使用storeToRefs(),它将为每个响应性属性创建引用。当你只使用 Store 的状态而不调用任何action时,它会非常有用。使用方法如下

<template>
	<div>
		<h1>vue组件</h1>
		{{ name }}
	</div>
</template>

<script setup>
//这里需要先引入
import { storeToRefs } from 'pinia'
import { useStudyStore } from '@/stores/study'
const store = useStudyStore();
//这样解构的属性将保持响应性
let { name } = storeToRefs(store);
// name.value 可以直接修改到Store中存储的值

</script>

如果有多条数据要更新状态,推荐使用$patch方式更新。因为Pinia的官方网站,已经明确表示$ patch的方式是经过优化的,会加快修改速度,对程序的性能有很大的好处。

<template>
	<div>
		<h1>A组件</h1>
		{{ num}}
		{{ arr }}
		<button @click='btn'>按钮</button>
	</div>
</template>
<script setup>
import { storeToRefs } from 'pinia'
import { useStudyStore } from '@/stores/study'
const store = useStudyS
let { num,arr }  = storeToRefs(store);
const btn = ()=>{
	//批量更新
	store.$patch(state=>{
		state.num++;
		state.arr.push({name:'Ghmin'});

	})
}
</script>

actions:对state里数据变化的业务逻辑,需求不同,编写逻辑不同。说白了就是修改state全局状态数据的。

import { defineStore } from 'pinia'

export const useStudyStore = defineStore('studyId', {
  state: () => {
    return {
      num: 0
    }
  },
  getters:{},
  actions:{
  	changeNum( val ){
  		this.num+= val;
  	}
  }
})
<template>
	<div>
		<h1>使用actions</h1>
		{{ num}}
		<button @click='add'>加99</button>
	</div>
</template>
<script setup>
import { storeToRefs } from 'pinia'
import { useStudyStore } from '@/stores/study'
const store = useStudyStore();
let { num}  = storeToRefs(store);
const add = ()=>{
	store.changeNum(10);
}
</script>

getters:和vuex的getters几乎类似,用来监视或者说是计算状态的变化的,有缓存的功能。

import { defineStore } from 'pinia'

export const useStudyStore = defineStore('studyId', {
  state: () => {
    return {
      num: 0,
    }
  },
  getters:{
  	numGetters(){
  		return this.counter + 999;
  	}
  },
  actions:{}
})
<template>
	<div>
	    <h1>getters的使用</h1>
		{{ num}}
		{{ numGetters}}
	</div>
</template>
<script setup>
import { storeToRefs } from 'pinia'
import { useStudyStore } from '@/stores/study'
const store = useStudyStore();
let { num,numGetters}  = storeToRefs(store);
</script>

三.数据持久化存储

使用pinia-plugin-persist实现数据持久化存储,具体使用请跳转Pinia持久化存储

数据持久化存储

### 使用 Pinia 实现数据持久化并结合本地存储(localStorage)的教程或示例 #### 1. 安装 Pinia 和插件 在项目中安装 Pinia 及其持久化插件 `pinia-plugin-persistedstate`,可以通过以下命令完成: ```bash npm install pinia pinia-plugin-persistedstate ``` #### 2. 配置 Pinia 并集成持久化插件 在项目的入口文件(如 `main.js` 或 `main.ts`)中,创建 Pinia 实例并引入持久化插件。以下是配置代码示例[^1]: ```javascript // main.js 或 main.ts import { createApp } from 'vue'; import { createPinia } from 'pinia'; import piniaPluginPersistedstate from 'pinia-plugin-persistedstate'; import App from './App.vue'; const pinia = createPinia(); pinia.use(piniaPluginPersistedstate); // 使用持久化插件 const app = createApp(App); app.use(pinia); app.mount('#app'); ``` #### 3. 定义 Store 并启用持久化 在定义 Store 时,通过 `persist: true` 或其他配置选项启用持久化功能。以下是一个完整的 Store 示例[^3]: ```javascript // stores/counter.js import { defineStore } from 'pinia'; export const useCounterStore = defineStore('counter', { state: () => ({ count: parseInt(localStorage.getItem('count')) || 0, // 初始化状态 }), actions: { increment() { this.count++; localStorage.setItem('count', this.count.toString()); // 手动同步到 localStorage }, decrement() { this.count--; localStorage.setItem('count', this.count.toString()); // 手动同步到 localStorage }, }, }); ``` 或者,使用 `pinia-plugin-persistedstate` 自动处理持久化逻辑[^2]: ```javascript // stores/counter.js import { defineStore } from 'pinia'; export const useCounterStore = defineStore('counter', { state: () => ({ count: 0, }), persist: true, // 启用持久化 }); ``` #### 4. 自定义存储方式 如果需要自定义存储方式(例如使用 `sessionStorage` 或其他 API),可以在创建 Pinia 实例时配置插件。以下是一个自定义存储的示例[^4]: ```javascript // main.js 或 main.ts import { createPinia } from 'pinia'; import { createPersistedState } from 'pinia-plugin-persistedstate'; const pinia = createPinia(); pinia.use(createPersistedState({ storage: { getItem(key) { return sessionStorage.getItem(key); // 使用 sessionStorage }, setItem(key, value) { sessionStorage.setItem(key, value); // 使用 sessionStorage }, removeItem(key) { sessionStorage.removeItem(key); // 使用 sessionStorage }, }, })); const app = createApp(App); app.use(pinia); app.mount('#app'); ``` #### 5. 注意事项 - 在使用 `pinia-plugin-persistedstate` 时,确保插件版本与 Pinia 版本兼容。 - 如果需要支持更复杂的存储逻辑(如加密存储),可以扩展插件的 `storage` 配置[^4]。 ---
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

琢鸣

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值