【Vue】pinia

ops/2024/9/24 20:24:46/

pinia_0">pinia

官网:https://pinia.vuejs.org/zh/
在这里插入图片描述

pinia__4">搭建 pinia 环境

第一步:npm install pinia --save

第二步:操作src/main.ts

import { createApp } from 'vue'
import App from './App.vue'/* 引入createPinia,用于创建pinia */
import { createPinia } from 'pinia'/* 创建pinia */
const pinia = createPinia()
const app = createApp(App)/* 使用插件 */{}
app.use(pinia)
app.mount('#app')

此时开发者工具中已经有了pinia选项


存储+读取数据

采用两个组件'Count.vue''JokeTalk.vue'来举例说明pinia的使用
在这里插入图片描述

  1. Store是一个保存:状态业务逻辑 的实体,每个组件都可以读取写入它。

  2. 它有三个概念:stategetteraction,相当于组件中的: datacomputedmethods

  3. 具体编码:src/store/count.ts

    // 引入defineStore用于创建store
    import {defineStore} from 'pinia'// 定义并暴露一个store
    export const useCountStore = defineStore('count',{// 动作actions:{},// 状态state(){return {sum:6}},// 计算getters:{}
    })
    
  4. 具体编码:src/store/jokeTalk.ts

    // 引入defineStore用于创建store
    import {defineStore} from 'pinia'// 定义并暴露一个store
    export const useTalkStore = defineStore('talk',{// 动作actions:{},// 状态state(){return {talkList:[{id: "qwerabc001",title:"去开家长会,过道的表扬榜上贴着几份优秀作业。有个学生这样造句——妈妈一拿起鸡毛掸子,爸爸就抱头鼠窜。\n我当时就笑了,翻到作业本的封面想看看是哪个小朋友,结果看到我儿子的名字。。。",},{id: "qwerabc002",title:"昨天带儿子去公园玩,为了锻炼他,路上我就没让他坐他的儿童车,而是让他推着往公园走。\n没想到才几分钟他就坚持不住了:“爸爸,我推不动了,能让我上车吗?”\n我扭头说道:“再坚持一下,马上就到了。",},{id: "qwerabc003",title:"家里来了个亲戚,十七八岁的大男孩,文静的坐在那,听说已经上高中了。\n我上前问道:“高几?”\n他脸一红说:“不,不,不搞。",},]}},// 计算getters:{}
    })
    
  5. 组件中使用state中的数据

    <template><h2>当前求和为:{{ sumStore.sum }}</h2>
    </template><script setup lang="ts" name="Count">// 引入对应的useXxxxxStore	import {useSumStore} from '@/store/sum'// 调用useXxxxxStore得到对应的storeconst sumStore = useSumStore()
    </script>
    
    <template><ul><li v-for="talk in talkStore.talkList" :key="talk.id">{{ talk.content }}</li></ul>
    </template><script setup lang="ts" name="Count">import {useTalkStore} from '@/store/talk'const talkStore = useTalkStore()
    </script>
    

5.4.【修改数据】(三种方式)

  1. 第一种修改方式,直接修改

    countStore.sum = 666
    
  2. 第二种修改方式:批量修改

    countStore.$patch({sum:999,school:'atguigu'
    })
    
  3. 第三种修改方式:借助action修改(action中可以编写一些业务逻辑)

    import { defineStore } from 'pinia'export const useCountStore = defineStore('count', {/*************/actions: {//加increment(value:number) {if (this.sum < 10) {//操作countStore中的sumthis.sum += value}},//减decrement(value:number){if(this.sum > 1){this.sum -= value}}},/*************/
    })
    
  4. 组件中调用action即可

    // 使用countStore
    const countStore = useCountStore()// 调用对应action
    countStore.increment(n.value)
    

5.5.【storeToRefs】

  • 借助storeToRefsstore中的数据转为ref对象,方便在模板中使用。
  • 注意:pinia提供的storeToRefs只会将数据做转换,而VuetoRefs会转换store中数据。
<template><div class="count"><h2>当前求和为:{{sum}}</h2></div>
</template><script setup lang="ts" name="Count">import { useCountStore } from '@/store/count'/* 引入storeToRefs */import { storeToRefs } from 'pinia'/* 得到countStore */const countStore = useCountStore()/* 使用storeToRefs转换countStore,随后解构 */const {sum} = storeToRefs(countStore)
</script>

5.6.【getters】

  1. 概念:当state中的数据,需要经过处理后再使用时,可以使用getters配置。

  2. 追加getters配置。

    // 引入defineStore用于创建store
    import {defineStore} from 'pinia'// 定义并暴露一个store
    export const useCountStore = defineStore('count',{// 动作actions:{/************/},// 状态state(){return {sum:1,school:'atguigu'}},// 计算getters:{bigSum:(state):number => state.sum *10,upperSchool():string{return this. school.toUpperCase()}}
    })
    
  3. 组件中读取数据:

    const {increment,decrement} = countStore
    let {sum,school,bigSum,upperSchool} = storeToRefs(countStore)
    

5.7.【$subscribe】

通过 store 的 $subscribe() 方法侦听 state 及其变化

talkStore.$subscribe((mutate,state)=>{console.log('LoveTalk',mutate,state)localStorage.setItem('talk',JSON.stringify(talkList.value))
})

5.8. 【store组合式写法】

import {defineStore} from 'pinia'
import axios from 'axios'
import {nanoid} from 'nanoid'
import {reactive} from 'vue'export const useTalkStore = defineStore('talk',()=>{// talkList就是stateconst talkList = reactive(JSON.parse(localStorage.getItem('talkList') as string) || [])// getATalk函数相当于actionasync function getATalk(){// 发请求,下面这行的写法是:连续解构赋值+重命名let {data:{content:title}} = await axios.get('https://api.uomg.com/api/rand.qinghua?format=json')// 把请求回来的字符串,包装成一个对象let obj = {id:nanoid(),title}// 放到数组中talkList.unshift(obj)}return {talkList,getATalk}
})

http://www.ppmy.cn/ops/39465.html

相关文章

负载或反向代理服务器如何配置XFF以获取终端真实IP

文章目录 XFF介绍工作原理注意事项 配置方式1. Nginx2. HAProxy3. F5 BIG-IP4. Radware注意事项 本文介绍如何在反向代理或负载中配置XFF&#xff0c;方便后端服务获取请求来源的真实IP XFF介绍 X-Forwarded-For&#xff08;简称XFF&#xff09;是一个非标准的HTTP头部字段&a…

短剧奔向小程序,流量生意如何开启?

随着移动互联网的飞速发展&#xff0c;小程序作为一种轻量级、易传播的应用形态&#xff0c;逐渐在各个领域展现出其独特的商业价值。而最近爆火的短剧小视频作为一种受众广泛的娱乐形式&#xff0c;与小程序结合后&#xff0c;不仅为观众提供了更为便捷的观看体验&#xff0c;…

go语言自定义排序接口Interface实现示例 sort.Sort(data Interface) 快速排序 pdqsort

go语言sort.Sort(data Interface) 排序接口自定义排序实现&#xff0c;golang里面的sort包中的Sort方法底层使用的是 pdqsort的一个快速排序算法&#xff0c; 我们可以将要排序的对象实现Interface接口后直接丢个这个函数即可自动按照我们指定的方式进行数据快速排序。 sort函…

C++入门(1)

前言 我们已经学习了C语言&#xff0c;而C与C语言有着千丝万缕的联系&#xff0c;那么我们废话不多说&#xff0c;正式进入C的学习 什么是C 我们之前学习过C语言&#xff0c;而C语言是结构化和模块化的语言&#xff0c;比较适合处理较小规模的程序。而对于相对复杂的问题和较…

Mac idea gradle解决异常: SSL peer shut down incorrectly

系统&#xff1a;mac 软件&#xff1a;idea 解决异常: SSL peer shut down incorrectly 查看有没有安装 gradle -v安装 根据项目gradle提示安装版本 brew install gradle7idea的配置 在settings搜索gradle&#xff0c;配置Local installation&#xff0c;选择自己的安装目录…

Hadoop集群部署

目录 准备 资源准备 实验架构 环境准备 实验步骤 &#xff08;一&#xff09;查看环境 1、检查防火墙是否关闭 2、检查三台虚拟机hosts文件 3、检查ssh环境 &#xff08;二&#xff09;部署hadoop集群 1、安装haoop 2、创建hdfs数据文件存储目录 3、修改配置文件 …

ICode国际青少年编程竞赛- Python-3级训练场-能量状态判断1

ICode国际青少年编程竞赛- Python-3级训练场-能量状态判断1 1、 for i in range(6):Spaceship.step(2)if not Item[i].broken():Spaceship.turnLeft()Spaceship.step(4)Spaceship.turnLeft()Spaceship.turnLeft()Spaceship.step(4)Spaceship.turnLeft()2、 for i in range(6)…

OpenCV | 项目 | 虚拟绘画

OpenCV | 项目 | 虚拟绘画 捕捉摄像头 如果在虚拟机中运行&#xff0c;请确保虚拟机摄像头打开。 #include<opencv2/opencv.hpp>using namespace cv; using namespace std;int main() {VideoCapture cap(0);Mat img;while(1) {cap.read(img);imshow("Image"…