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

一.安装及使用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 数据持久化储存插件(pinia-plugin-persistedstate)的详细代码配置。 首先,您需要安装 `pinia-plugin-persistedstate` 插件: ``` npm install pinia-plugin-persistedstate ``` 然后,在您的 Vue.js 项目中,您需要创建一个 Pinia 实例,并使用 `use` 方法加载 `pinia-plugin-persistedstate` 插件: ```javascript import { createPinia } from 'pinia' import { createPersistedState } from 'pinia-plugin-persistedstate' const pinia = createPinia() pinia.use(createPersistedState({ key: 'my-app-state', // 存储在本地存储中的键名 initialState: () => ({ // 初始状态 count: 0, todos: [] }), storage: window.localStorage // 存储在哪个存储中(可选) })) ``` 以上代码中,我们使用了 `createPersistedState` 方法创建一个持久化状态插件实例,并将其传递给 `pinia.use()` 方法以加载插件。 在 `createPersistedState` 方法中,您需要传递一个对象参数,包含以下选项: - `key`:在本地存储存储状态的键名。 - `initialState`:状态的初始值。这可以是一个对象或一个函数,该函数返回一个对象。 - `storage`:指定存储状态的存储对象。默认是 `window.localStorage`。 现在,您可以在 Pinia store 中使用持久状态了。例如: ```javascript import { defineStore } from 'pinia' export const useCounterStore = defineStore('counter', { state: () => ({ count: 0 }), actions: { increment() { this.count++ }, decrement() { this.count-- } } }) ``` 以上代码中,我们定义了一个简单的计数器存储。现在,我们可以在组件中使用 `useCounterStore`: ```html <template> <div> <p>Count: {{ count }}</p> <button @click="increment">+</button> <button @click="decrement">-</button> </div> </template> <script> import { useCounterStore } from './store' export default { setup() { const counterStore = useCounterStore() return { count: counterStore.count, increment: counterStore.increment, decrement: counterStore.decrement } } } </script> ``` 现在,每当用户增加或减少计数器时,状态都会自动持久化到本地存储中。当用户刷新页面或重新打开应用程序时,状态将从本地存储中自动加载。
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

琢鸣

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

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

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

打赏作者

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

抵扣说明:

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

余额充值