Vue3状态管理库--Pinia

Pinia快速入门

一、什么是Pinia ?

Pinia 是 Vue 的专属的最新状态管理库 ,是 Vuex 状态管理工具的替代品。

Pinia官网链接

image-20240326193234827

  1. 提供更加简单的API (去掉了 mutation )
  2. 提供符合组合式风格的API (和 Vue3 新语法统一)
  3. 去掉了 modules 的概念,每一个 store 都是一个独立的模块
  4. 搭配 TypeScript 一起使用提供可靠的类型推断

二、创建空Vue项目并安装Pinia

以下步骤均可在官方文档中查询。

1. 创建空Vue项目

npm init vue@latest

2. 安装Pinia并注册

npm install pinia
import { createPinia } from 'pinia'

const app = createApp(App)
// 以插件的形式注册
app.use(createPinia())
app.use(router)
app.mount('#app')

三、使用Pinia实现计数器

核心步骤:

  1. 定义store
  2. 组件使用store

1- 定义store

import { defineStore } from 'pinia'
import { ref } from 'vue'

export const useCounterStore = defineStore('counter', ()=>{
  // 数据 (state)
  const count = ref(0)

  // 修改数据的方法 (action)
  const increment = ()=>{
    count.value++
  }

  // 以对象形式返回
  return {
    count,
    increment
  }
})

2- 组件使用store

<script setup>
  // 1. 导入use方法
	import { useCounterStore } from '@/stores/counter'
  // 2. 执行方法得到store store里有数据和方法
  const counterStore = useCounterStore()
</script>

<template>
	<button @click="counterStore.increment">
    {{ counterStore.count }}
  </button>
</template>

image-20240326202354120

四、getters

Pinia中的 getters 直接使用 computed函数进行模拟

// 数据(state)
const count = ref(0) 
// getter (computed)
const doubleCount = computed(() => count.value * 2)

image-20240326203005973

五、异步action

思想:action函数既支持同步也支持异步,和在组件中发送网络请求写法保持一致
步骤:

  1. store中定义action
  2. 组件中触发action

1- store中定义action

const API_URL = 'http://geek.itheima.net/v1_0/channels'

export const useCounterStore = defineStore('counter', ()=>{
  // 数据
  const list = ref([])
  // 异步action
  const loadList = async ()=>{
    const res = await axios.get(API_URL)
    list.value = res.data.data.channels
  }
  
  return {
    list,
    loadList
  }
})

2- 组件中调用action

<script setup>
	import { useCounterStore } from '@/stores/counter'
  const counterStore = useCounterStore()
  // 调用异步action
  counterStore.loadList() 
</script>

<template>
	<ul>
    <li v-for="item in counterStore.list" :key="item.id">{{ item.name }}</li>
  </ul>
</template>

image-20240326205052718

六、storeToRefs保持响应式解构

直接基于store进行解构赋值,响应式数据(state和getter)会丢失响应式特性,使用storeToRefs辅助保持响应式

image-20240326205613801

<script setup>
  import { storeToRefs } from 'pinia'
	import { useCounterStore } from '@/stores/counter'
  const counterStore = useCounterStore()
  // 使用它storeToRefs包裹之后解构保持响应式
  const { count } = storeToRefs(counterStore)

  const { increment } = counterStore
  
</script>

<template>
	<button @click="increment">
    {{ count }}
  </button>
</template>

需要注意的是:storeToRefs只能结构数据,并不能解构方法,解构方法还是使用原来的方式。

  • 5
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Vue 3中,`pinia-plugin-persistedstate`是一个用于持久化状态的Pinia插件,它允许你在用户关闭和重新打开应用时保存和恢复数据。关于设置Pinia状态的时效,你需要明确你是指的状态持久化的时间范围,例如: 1. **默认保存间隔**:这个插件通常会自动保存状态到浏览器的localStorage或 sessionStorage中。默认情况下,Pinia-PersistedState可能没有特定的保存间隔,但你可以通过配置自定义保存策略。 2. **手动触发保存**:你可以选择在特定场景(如组件卸载或页面刷新前)调用保存方法,这可以让你控制保存的时机。 3. **失效时间**:对于敏感信息,你可能希望设置一个过期时间,超过这个时间后数据会被清除。这通常不是由Pinia-PersistedState直接处理,而是通过在存储选项中设置`maxAge`属性来实现,然后在加载数据时检查是否已过期。 为了具体设置pinia状态的时效,你需要在配置插件时进行以下操作: ```javascript import { createApp } from 'vue'; import { useStore } from '@pinia/core'; import { persistedState } from 'pinia-plugin-persistedstate'; const store = defineStore('myStore', { // ...定义你的状态和方法 }); // 使用 persistedState 插件 createApp({ // ...其他配置 }) .use(store) .use(persistedState, { key: 'myStore', // 存储的键名 // 可选的保存策略,如自动保存间隔、过期时间等 // 例如: // localStorage: { maxAge: 24 * 60 * 60 * 1000 }, // 一天后数据过期 }); ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

曼诺尔雷迪亚兹

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

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

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

打赏作者

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

抵扣说明:

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

余额充值