当前位置: 首页 > news >正文

Vue3 :Pinia入门

Vue3 :Pinia入门

Date: May 11, 2023
Sum: Pinia概念、实现counter、getters、异步action、storeToRefs保持响应式解构


什么是Pinia

Pinia 是 Vue 的专属状态管理库,可以实现跨组件或页面共享状态,是 vuex 状态管理工具的替代品,和 Vuex相比,具备以下优势

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

简单说,就是原本Vuex有 state mutations actions getters modules

现在Pinia简化成了 state actions getters

中文文档:https://pinia.vuejs.org/zh




创建空Vue项目并安装Pinia

1. 创建空Vue项目

npm init vue@latest

Untitled



2. 安装Pinia并注册

npm i pinia
import { createPinia } from 'pinia'// 创建Pinia实例
const pinia = createPinia()// 创建根实例
const app = createApp(App)// 以插件的形式注册
app.use(pinia).mount('#app')



实现counter

核心步骤:

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

1- 定义store

counter.js

import { defineStore } from 'pinia'
import { ref } from 'vue'export const useCounterStore = defineStore('counter', ()=>{// 数据 (state)const count = ref(0)// 修改数据的方法 (action)由于这是组合式写法,所以普通函数就是actionconst increment = ()=>{ count.value++}// 以对象形式返回return {count,increment}
})

理解:

定义仓库counter返回的是一个函数,这里采用useCounterStore接收

在定义store的时候,我们采取和组合式api一样的写法,不过需要return回需要的数据与方法。

2- 组件使用store

App.vue

<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>

案例:

counter.js

// 导入一个方法 defineStore
import { defineStore } from 'pinia'
import { ref } from 'vue'export const useCounterStore =  defineStore('counter' , () => {// 定义数据(state)const count = ref(0)// 定义修改数据的方法(action 同步+异步)const increment = () => {count.value++}// 以对象的方式return供组件使用return {count,increment}
})

App.vue

<template><button @click="counterStore.increment">{{ counterStore.count }}</button>
</template><script setup>
// 1. 导入 use 打头的方法
import { useCounterStore } from '@/store/counter'
// 2. 执行方法得到store实例对象
const counterStore = useCounterStore()
console.log(counterStore);
</script><style></style>

效果:实现一个计数器




实现getters

getters直接使用计算属性即可实现

实现:这里的doubleCount永远会随着count的变化而变化

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



异步action

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

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

  • 接口地址:http://geek.itheima.net/v1_0/channels

  • 请求方式:get

  • 请求参数:无

    需求:在Pinia中获取频道列表数据并把数据渲染App组件的模板中

Untitled

1- store中定义action

const API_URL = 'http://geek.itheima.net/v1_0/channels'export const useCounterStore = defineStore('counter', ()=>{// 数据const list = ref([])// 异步actionconst 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()// 调用异步actioncounterStore.loadList()
</script><template><ul><li v-for="item in counterStore.list" :key="item.id">{{ item.name }}</li></ul>
</template>



storeToRefs保持响应式解构

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

问题

Untitled

原因

store是一个用reactive包装的对象

上面我们采用解构的方式从 counterStore 中取出 count msg

具体操作:

<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>

理解:数据和方法如何解构赋值

数据解构赋值:

采用解构赋值,并采用方法包裹

方法解构赋值:

直接解构赋值即可

App.vue

<template><button @click="increment">{{ count }}</button><p>{{ doubleCount }}</p><ul><li v-for="item in counterStore.getList" :key="item.id">{{ item.name }}</li></ul>
</template><script setup>// 1. 导入 use 打头的方法import { useCounterStore } from '@/stores/counter'import { onMounted } from 'vue'import { storeToRefs } from 'pinia'// 2. 执行方法得到store实例对象const counterStore = useCounterStore()// 数据解构:// 直接解构赋值(会造成响应式丢失)// 这里采用方法包裹(可以保持响应式的更新)const { count, doubleCount } = storeToRefs(counterStore)// 方法解构:// 注: 方法解构直接从counterStore中解构赋值即可const { increment } = counterStoreonMounted(() => {counterStore.getList()})
</script>

效果:

Untitled

注意:

如图所示,直接解构赋值,则只会传值回来。而采用解构赋值,并采用方法包裹,则传回对象。

总结:

  1. pinia是用来做什么的?

    集中状态管理工具,新一代的vuex

  2. Pinia中还需要mutation吗?

    不需要,action既支持同步也支持异步
    Pinia如何实现getter?
    computed计算属性函数

  3. Pinia产生的Store如何解构赋值数据保持响应式?

storeToRefs




Pinia的调试

Vue官方的 dev-tools 调试工具 对 Pinia直接支持,可以直接进行调试

Untitled




Pinia持久化插件

官方文档:https://prazdevs.github.io/pinia-plugin-persistedstate/zh/

  1. 安装插件 pinia-plugin-persistedstate
npm i pinia-plugin-persistedstate
  1. 使用 main.js
import persist from 'pinia-plugin-persistedstate'
...
app.use(createPinia().use(persist))

main.js 完整配置

import { createPinia } from 'pinia'
import { createApp } from 'vue'
import App from './App.vue'
import persist from 'pinia-plugin-persistedstate'const pinia = createPinia()
const app = createApp(App)app.use(pinia.use(persist)).mount('#app')
  1. 配置 store/counter.js 开启当前模块的持久化
import { defineStore } from 'pinia'
import { computed, ref } from 'vue'export const useCounterStore = defineStore('counter', () => {...return {count,doubleCount,increment}
}, {persist: true
})
  1. 其他配置,看官网文档即可
persist: {key: 'name'  // 修改本地存储的唯一标识paths: ['count']  // 存储的是哪些数据
}

补充:查看浏览器存储信息

在 Application 中查看存储信息

Untitled

http://www.lryc.cn/news/119295.html

相关文章:

  • Java线程池的类型和使用
  • QT的信号槽的四种写法和五种链接方式
  • Vue+SpringBoot项目开发:后台登陆功能的实现(二)
  • arcgis pro 3.0.2 安装及 geemap
  • oracle插入多表(insert all/first)
  • 工业以太网交换机-SCALANCE X200 环网组态
  • 利用 Splashtop Enterprise 改善公司的网络安全
  • mqbroker.cmd闪退(mqnamesrv.cmd能正常启动)
  • LeetCode--HOT100题(26)
  • HTTP 请求方法详解
  • 孤立随机森林(Isolation Forest)(Python实现)
  • 小程序如何自定义分享内容
  • SpringBoot整合WebSocket详解
  • 伪原创神码ai怎么样【php源码】
  • Air001基于Keil环境开发,使用airisp串口命令行烧录
  • kubernetes 中的事件(event)简介以及如何收集event和基于event告警
  • C++小游戏贪吃蛇源码
  • 【密码学】穴居人密码
  • neo4j的CQL命令实例演示
  • vue3+ts使用antv/x6
  • wsl1 ubuntu通过宿主机代理连接外网
  • ubuntu20.04 opencv4.2 安装笔记
  • ubuntu安装nginx以及php的部署
  • IntelliJ IDEA 2021/2022关闭双击shift全局搜索
  • HTML 元素中的name 属性
  • 快速上手React:从概述到组件与事件处理
  • K8S系列文章之 离线安装自动化工具Ansible
  • mysql8.0.3集群搭建
  • vue中router路由的原理?两种路由模式如何实现?(vue2) -(上)
  • 消息队列(3) -封装数据库的操作