Vue从入门到实战Day12

一、Pinia快速入门

1. 什么是Pinia

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

1. 提供更加简单的API(去掉了mutation)

2. 提供符合组合式风格的API(和Vue3新语法统一)

3. 去掉了modules的概念,每一个store都是一个独立的模块

4. 配合TypeScript更加友好,提供可靠的类型推断

2. 手动添加Pinia到Vue项目

在实际开发项目的时候,关于Pinia的配置,可以在项目创建时自动添加

1. 使用Vite创建一个空的Vue3项目

npm create vue@latest

2. 按照官方文档安装Pinia到项目中

①安装Pinia

npm install pinia

②创建一个 pinia 实例 (根 store) 并将其传递给应用 - mian.js

import { createApp } from 'vue'
import { createPinia } from 'pinia'
import App from './App.vue'const pinia = createPinia()  // 创建Pinia实例
const app = createApp(App)  // 创建根实例app.use(pinia)  // pinia插件的安装配置
app.mount('#app')  // 视图的挂载

3. Pinia基础使用 - 计数器案例

1. 定义store

src/store/counter.js

import { defineStore } from 'pinia'
import { ref, computed } from 'vue'// 定义store
// defineStore(仓库的唯一标识, () => { ... })export const useCounterStore =  defineStore('counter', () => {// 声明数据 - stateconst count = ref(6)// 声明操作数据的方法 - action(普通函数)const addCount = () => {count.value++}const subCount = () => count.value--// 声明基于数据派生的计算属性 - getters(computed)const double = computed(() => count.value * 2)// 声明数据 - stateconst msg = ref('hello Pinia')return {count, addCount,subCount,double,msg}
})

2. 组件使用store

App.vue

<script setup>
import Son1Com from '@/components/Son1Com.vue'
import Son2Com from '@/components/Son2Com.vue'
import { useCounterStore } from '@/store/counter'const counterStore = useCounterStore()
console.log(counterStore)
</script><template><div><h3>App.vue根组件- {{ counterStore.count }}- {{ counterStore.msg }}</h3><Son1Com></Son1Com><Son2Com></Son2Com></div>
</template><style scoped></style>

src/components/Son1Com.vue

<script setup>
import { useCounterStore } from '@/store/counter'const counterStore = useCounterStore()
</script><template><div>我是Son1Com.vue - {{ counterStore.count }}- {{ counterStore.double }}<button @click="counterStore.addCount">+</button></div>
</template><style scoped></style>

src/components/Son2Com.vue

<script setup>
import { useCounterStore } from '@/store/counter'const counterStore = useCounterStore()
</script><template><div>我是Son2Com.vue- {{ counterStore.count }}<button @click="counterStore.subCount">-</button></div>
</template><style scoped></style>

4. action异步实现

编写方式:异步action函数的写法和组件中获取异步数据的写法完全一致

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

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

示例代码:

src/store/channel.js

import { defineStore } from 'pinia'
import { ref } from 'vue'
import axios from 'axios'export const useChannelStore = defineStore('channel', () => {// 声明数据const channelList = ref([])// 声明操作数据的方法const getList = async () => {// 支持异步const { data: {data} } = await axios.get('http://geek.itheima.net/v1_0/channels')channelList.value = data.channelsconsole.log(data.channels)}// 声明getters相关return {channelList,getList}
})

App.vue

<script setup>
import Son1Com from '@/components/Son1Com.vue'
import Son2Com from '@/components/Son2Com.vue'
import { useCounterStore } from '@/store/counter'
import { useChannelStore } from '@/store/channel.js'const counterStore = useCounterStore()
const channelStore = useChannelStore()
// console.log(counterStore)</script><template><div><h3>App.vue根组件- {{ counterStore.count }}- {{ counterStore.msg }}</h3><Son1Com></Son1Com><Son2Com></Son2Com><hr><button @click="channelStore.getList">获取频道数据</button><ul><li v-for="item in channelStore.channelList" :key="item.id">{{ item.name }}</li></ul></div>
</template><style scoped></style>

5. storeToRefs()

为了从 store 中提取属性时保持其响应性,你需要使用 storeToRefs()。它将为每一个响应式属性创建引用。当你只使用 store 的状态而不调用任何 action 时,它会非常有用。请注意,你可以直接从 store 中解构 action,因为它们也被绑定到 store 上:

<script setup>
import { storeToRefs } from 'pinia'
const store = useCounterStore()
// `name` 和 `doubleCount` 是响应式的 ref
// 同时通过插件添加的属性也会被提取为 ref
// 并且会跳过所有的 action 或非响应式 (不是 ref 或 reactive) 的属性
const { name, doubleCount } = storeToRefs(store)
// 作为 action 的 increment 可以直接解构
const { increment } = store
</script

示例代码:

App.vue

<script setup>
import { storeToRefs } from 'pinia'
import Son1Com from '@/components/Son1Com.vue'
import Son2Com from '@/components/Son2Com.vue'
import { useCounterStore } from '@/store/counter'
import { useChannelStore } from '@/store/channel.js'const counterStore = useCounterStore()
const channelStore = useChannelStore()// 此时,直接结构,不处理,数据会丢失响应式
// const { count, msg } = counterStore
const { count, msg } = storeToRefs(counterStore)
const { channelList } = storeToRefs(channelStore)
const { getList } = channelStore</script><template><div><h3>App.vue根组件- {{ count }}- {{ msg }}</h3><Son1Com></Son1Com><Son2Com></Son2Com><hr><button @click="getList">获取频道数据</button><ul><li v-for="item in channelList" :key="item.id">{{ item.name }}</li></ul></div>
</template><style scoped></style>

6. Pinia的调试

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

Pinia持久化插件

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

注:要先安装Pinia,且Pinia版本在2.0.0以上

1. 安装插件 pinia-plugin-persistedstate

npm i pinia-plugin-persistedstate

2. main.js使用

import persist from 'pinia-plugin-persistedstate'
...
app.use(createPinia().use(persist))

3. store仓库中,persist: true开启

如src/store/counter.js

import { defineStore } from 'pinia'
import { ref, computed } from 'vue'// 定义store
// defineStore(仓库的唯一标识, () => { ... })export const useCounterStore =  defineStore('counter', () => {// 声明数据 - stateconst count = ref(6)// 声明操作数据的方法 - action(普通函数)const addCount = () => {count.value++}const subCount = () => count.value--// 声明基于数据派生的计算属性 - getters(computed)const double = computed(() => count.value * 2)// 声明数据 - stateconst msg = ref('hello Pinia')// 声明操作数据的方法 - action// 声明基于数据派生的计算属性 - gettersreturn {count, addCount,subCount,double,msg}
},
{// persist: true,  // 开启当前模块的持久化persist: {key: 'hm-counter',  // 修改本地存储的唯一标识// 这个 store 将被持久化存储在 sessionStorage中// storage: sessionStorage,paths: ['count'],  // 存储的是哪些数据}
})

7. 总结

1. Pinia是用来做什么的?

答:新一代的状态管理工具,替代vuex

2. Pinia中还需要mutation吗?

答:不需要,action既支持同步也支持异步

3. Pinia如何实现getter?

答:computed计算属性函数

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

答:storeToRefs

5. Pinia如何快速实现持久化?

答:pinia-plugin-persistedstate

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/840055.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

C++|设计模式(二)|简单工厂和工厂方法模式

本文探讨两种广泛使用的创建型模式——简单工厂模式和工厂方法模式&#xff0c;解释他们的实现细节、优势以及应用场景。 在下一篇文章中&#xff0c;我会补充抽象工厂模式&#xff0c;其实工厂模式主要就是为了封装对象的创建过程&#xff0c;如果我们不进行封装&#xff0c;…

人工智能应用-实验7-胶囊网络分类minst手写数据集

文章目录 &#x1f9e1;&#x1f9e1;实验内容&#x1f9e1;&#x1f9e1;&#x1f9e1;&#x1f9e1;代码&#x1f9e1;&#x1f9e1;&#x1f9e1;&#x1f9e1;分析结果&#x1f9e1;&#x1f9e1;&#x1f9e1;&#x1f9e1;实验总结&#x1f9e1;&#x1f9e1; &#x1f9…

Python TCP编程简单实例

客户端&#xff1a;创建TCP链接时&#xff0c;主动发起连接的叫做客户端 服务端&#xff1a;接收客户端的连接 连接其他服务器 可以通过tcp连接其他服务器。 示例&#xff1a; import socket# 1.创建一个socket # 参数1&#xff1a;指定协议 AF_INET&#xff08;ipv4&#…

LeetCode1466重新规划路线

题目描述 n 座城市&#xff0c;从 0 到 n-1 编号&#xff0c;其间共有 n-1 条路线。因此&#xff0c;要想在两座不同城市之间旅行只有唯一一条路线可供选择&#xff08;路线网形成一颗树&#xff09;。去年&#xff0c;交通运输部决定重新规划路线&#xff0c;以改变交通拥堵的…

vite项目怎么build打包成不同环境的代码?从而适配不同环境api接口

在开发 Web 应用的过程中&#xff0c;我们需要在不同的环境中运行和测试我们的应用程序&#xff08;如开发环境、测试环境和生产环境&#xff09;。每个环境都有其特定的 API 接口和配置。Vite&#xff0c;一个基于 ESBuild 的前端构建工具&#xff0c;可以帮助我们实现这个需求…

判断当前系统是linux、windows还是MacOS (python)

在很多情况下&#xff0c;需要在python中获取当前系统的类型&#xff0c;用于判断是unix/windows/mac或者java虚拟机等&#xff0c;python中提供了os.name&#xff0c; sys.platform&#xff0c; platform.system等方式 sys sys.platform会返回当前系统平台的标识符&#xff…

Linux系统——面试题分享

目录 1.现在给你三百台服务器&#xff0c;你怎么对他们进行管理&#xff1f; 2.简述 raid0 raid1 raid5 三种工作模式的工作原理及特点 2.1RAID 0 ——可以是一块盘和 N 个盘组合 2.2RAID 1 ——只能2块盘&#xff0c;盘的大小可以不一样&#xff0c;以小的为准 2.3RAID 5 …

ganglia的安装使用

1.集群内分别安装epel-release依赖&#xff0c;更新yum源 sudo yum -y install epel-release 2&#xff0e;各节点上分别安装gmond sudo yum -y install ganglia-gmond 3.监控节点上安装gmetad和web(这里安装在node1上) sudo yum -y install ganglia-gmetad sudo yum -y insta…

现代密码学——消息认证和哈希函数

1.概述 1.加密-->被动攻击&#xff08;获取消息内容、业务流分析&#xff09; 消息认证和数字签名-->主动攻击&#xff08;假冒、重放、篡改、业务拒绝&#xff09; 2.消息认证作用&#xff1a; 验证消息源的真实性&#xff0c; 消息的完整性&#xff08;未被篡改…

Docker基本操作命令

Docker 是一个开源的应用容器引擎&#xff0c;允许开发者打包他们的应用以及应用的依赖包到一个可移植的容器中&#xff0c;然后发布到任何流行的 Linux 机器或者 Windows 服务器上。这使得应用可以在几乎任何地方以相同的方式运行。今天&#xff0c;我们将详细探讨一些基本的 …

第七步 实现打印函数

文章目录 前言一、如何设计我们的打印函数&#xff1f;二、实践检验&#xff01; 查看系列文章点这里&#xff1a; 操作系统真象还原 前言 现在接力棒意见交到内核手中啦&#xff0c;只不过我们的内核现在可谓是一穷二白啥都没有&#xff0c;为了让我们设计的内核能被看见被使用…

数据防泄露解决方案分享

在当今高度数字化和互联的商业环境中&#xff0c;数据防泄密已成为企业保护财产、维护客户隐私和遵守合规要求的重要一环。数据防泄密不仅关乎企业的经济利益&#xff0c;更涉及用户个人信息安全、商业机密保护以及国家安全等核心问题。能做好数据防泄露&#xff0c;对于提升企…

深入解析 Java 中的 Synchronized:原理、实现与性能优化

深入解析 Java 中的 Synchronized&#xff1a;原理、实现与性能优化 Synchronized 介绍Synchronized 的三种使用方式普通同步方法&#xff08;实例方法&#xff09;静态同步方法同步方法块 Synchronized的底层实现原理1. Monitor锁2. 对象头结构3. 锁的状态4. 锁的升级和膨胀过…

rbd块设备数据IO流程(client端)

一、rbd内核驱动写入流程 1&#xff09;初始化 首先是rbd驱动的初始化工作&#xff1a;包括验证libceph的兼容性&#xff0c;分配内存&#xff0c;在sysfs中创建块设备控制文件、创建工作队列rbd_wq并调用INIT_WORK初始化它 module_init(rbd_init); static int __init rbd_i…

持续总结中!2024年面试必问 20 道 Redis面试题(六)

上一篇地址&#xff1a;持续总结中&#xff01;2024年面试必问 20 道 Redis面试题&#xff08;五&#xff09;-CSDN博客 十一、Redis集群的原理是什么&#xff1f; 集群是一种分布式系统架构&#xff0c;它由多个节点组成&#xff0c;这些节点共同工作以提供高可用性、扩展性…

启动docker报错:Failed to listen on Docker Socket for the API.

说明&#xff1a; 1、安装部署docker完成后&#xff0c;启动docker报错&#xff1a;Failed to listen on Docker Socket for the API&#xff0c;如下图所示&#xff1a; 2、将SocketGroupdocker更改成&#xff1a;SocketGrouproot即可 一、解决方法&#xff1a; 1、执行命令…

舵机(结构,原理,控制方法)

介绍 舵机&#xff0c;全称为伺服马达&#xff08;Servo Motor&#xff09;&#xff0c;是一种能够精确控制角度或位置的电动机。它广泛应用于模型制作、机器人技术、工业自动化等领域。舵机通过接收控制信号&#xff0c;将其转化为机械运动&#xff0c;从而实现精确的控制。 …

代码随想录算法训练营第三天| 203.移除链表元素、 707.设计链表、 206.反转链表

203.移除链表元素 题目链接&#xff1a; 203.移除链表元素 文档讲解&#xff1a;代码随想录 状态&#xff1a;没做出来&#xff0c;做题的时候定义了一个cur指针跳过了目标val遍历了一遍链表&#xff0c;实际上并没有删除该删的节点。 错误代码&#xff1a; public ListNode re…

Java面试题:如何确定核心线程数

如何确定核心线程数 IO密集型任务 文件读写,DB读写,网络请求等 CPU密集型任务 计算型代码,Bitmap转换,Gson转换等 设置策略 N为cpu的核数 IO密集型任务,一般设置核心线程数大小设置为2N1 并发不高,任务执行时间长 不需要占用大量cpu,所以可以分配多个线程 CPU密集型任…