Vuex和Pinia

Vuex概述

vuex是一个vue的状态管理工具,状态就是数据(多组件共享数据)。

优势:

  • 共同维护一份数据,数据集中化管理
  • 响应式变化
  • 操作简洁(vuex提供了一些辅助函数)

vuex的使用

安装vuex插件

yarn add vuex@3

创建vuex模块文件

新建store/index.js专门存放vuex

创建仓库

import Vue from 'vue'
import Vuex from 'vuex'Vue.use(Vuex)const store = new Vuex.Store()export default store

main.js导入挂载

import Vue from 'vue'
import App from './App.vue'
import store from '@/store/index'Vue.config.productionTip = falsenew Vue({render: h => h(App),store
}).$mount('#app')

state状态

1.提供数据

state提供唯一的公共数据源,所有共享的数据都要统一放到Store中的stare中储存。

在state对象中可以添加我们要共享的数据。

const store = new Vuex.Store({state: {title: '大标题',count: 100}
})

2.使用数据

  1. 通过store直接访问
  2. 通过辅助函数(简化)

获取store:

  1. this.$store
  2. import 导入 stroe

直接访问

<template><div><p>数据:{{ $store.state.count }}</p><Son1Component></Son1Component><Son2Component></Son2Component></div>
</template>

辅助函数mapstate

mapstate是辅助函数,帮助我们把store中的数据自动映射到组件的计算机属性中。

导入mapState

import { mapState } from 'vuex'

通过对象的方式映射

  computed: {...mapState(['count', 'title'])}

在模板中使用

<template><div><p>数据:{{ count }}</p><Son1Component></Son1Component><Son2Component></Son2Component></div>
</template>

mutations

1.定义mutations对象,对象中存放修改state的方法

import Vue from 'vue'
import Vuex from 'vuex'Vue.use(Vuex)const store = new Vuex.Store({state: {title: '大标题',count: 100},mutations: {addcount (state) {state.count += 1},subcount (state) {state.count -= 1}}
})export default store

2.组件中提交调用mutations

<template><div><p>数据:{{ this.$store.state.count }}</p>
<button @click="handleAdd">+1</button></div>
</template><script>
export default {name: 'Son1Component',methods: {handleAdd () {this.$store.commit('addcount')}}
}
</script>

mutations传参语法

提交mutations是可以传递参数的'this.$store,commit('xxx',参数)'

1.提供mutation函数(带参数—提交载荷payload)

import Vue from 'vue'
import Vuex from 'vuex'Vue.use(Vuex)const store = new Vuex.Store({state: {title: '大标题',count: 100},mutations: {addcount (state, n) {state.count += n},subcount (state, n) {state.count -= n}}
})export default store
<template><div><p>数据:{{ this.$store.state.count }}</p>
<button @click="handleAdd(1)">+1</button>
<button @click="handleAdd(5)">+5</button></div>
</template><script>
export default {name: 'Son1Component',methods: {handleAdd (n) {this.$store.commit('addcount', n)}}
}
</script>

传递多个参数时,可以包装成一个对象传递

handleAdd (n) {this.$store.commit('addcount', {count: n,msg: 'haha'})}
    addcount (state, obj) {state.count += obj.countconsole.log(obj.msg)}

input的实时输入更新

输入框渲染

<input :value="count" @input="handInput" type="text" >

监听输入获取内容 

  methods: {handInput (e) {this.$store.commit('changecount', e.target.value)}

封装mutation处理函数 

  changecount (state, newcount) {state.count = newcount}

辅助函数mapMutations

mapMutations和mapState很像,它是把位于mutations中的方法提取了出来,映射到组件methods中

<template><div><p>数据:{{ this.$store.state.count }}</p><button @click="subcount(1)">-1</button></div>
</template><script>
import { mapMutations } from 'vuex'
export default {name: 'Son1Component',methods: {...mapMutations(['subcount'])}
}
</script>

actions

处理异步处理,mutations必须是同步的(便于监测数据变化,记录调试)

1.提供action方法

  actions: {changecountactions (context, num) {setTimeout(() => {context.commit('changecount', num)}, 1000)}}

在页面中dispath调用

    handchange (n) {this.$store.dispatch('changecountactions', n)}

辅助函数mapActions

mapActions是把位于actions中的方法提供了出来,映射到组件methods中

<template><div><p>数据:{{ this.$store.state.count }}</p><button @click="subcount(1)">-1</button><button @click="changecountactions(888)">一秒改成888</button></div>
</template><script>
import { mapMutations, mapActions } from 'vuex'
export default {name: 'Son1Component',methods: {...mapMutations(['subcount']),...mapActions(['changecountactions'])}
}
</script>

getters

类似于计算属性

除了state之外,有时我们还需要从state中派生出一些状态,这些状态是依赖state的,此时会用到getters。

定义getters

  1. getters函数的第一个参数是state
  2. getters函数必须要有返回值
  getters: {filterList (state) {return state.list.filter(item => item > 5)}}

访问getters

  1. 通过store访问getters
  2. 通过辅助函数mapGetters映射
<div>{{ $store.getters.filterList }}</div>
<template><div><p>数据:{{ this.$store.state.count }}</p><button @click="subcount(1)">-1</button><button @click="changecountactions(888)">一秒改成888</button><hr><div>{{ filterList }}</div></div>
</template><script>
import { mapMutations, mapActions, mapGetters } from 'vuex'
export default {name: 'Son1Component',methods: {...mapMutations(['subcount']),...mapActions(['changecountactions'])},computed: {...mapGetters(['filterList'])}
}
</script>

Pinia

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

优点:

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

手动添加Pinia到Vue项目

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

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

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

yarn add pinia
# 或者使用 npm
npm install pinia
import './assets/main.css'import { createApp } from 'vue'
import {createPinia} from 'pinia'
import App from './App.vue'const pinia = createPinia()
const app = createApp(App)
app.use(pinia).mount('#app')

 Pinia基础使用

1.定义store

import { defineStore } from 'pinia'
import { ref } from 'vue'export const usecounterstore = defineStore('counter',()=>{const count = ref(100)return {count}
})

2.组件使用store

<script setup>
import son1 from "@/components/son1.vue"
import son2 from "@/components/son2.vue"
import {usecounterstore} from "@/store/counter"
const counterstore = usecounterstore()
</script><template>
<div><h3>数据:{{ counterstore.count }}</h3><son1></son1><son2></son2>
</div>
</template>
import { defineStore } from 'pinia'
import { ref,computed } from 'vue'export const usecounterstore = defineStore('counter',()=>{// 声明数据stateconst count = ref(100)// 声明操作数据的方法active(普通函数)const addcount = ()=>count.value++const subcount = ()=>count.value--//声明基于数据派生的计算属性getters(computed) const double = computed(() => count.value*2)return {count,addcount,subcount,double}
})

active异步实现

import { defineStore } from 'pinia'
import { ref,computed } from 'vue'export const usecounterstore = defineStore('counter',()=>{// 声明数据stateconst count = ref(100)// 声明操作数据的方法active(普通函数)const addcount = ()=>count.value++const subcount = ()=>count.value--//声明基于数据派生的计算属性getters(computed) const double = computed(() => count.value*2)return {count,addcount,subcount,double}
})
<script setup>
import son1 from "@/components/son1.vue"
import son2 from "@/components/son2.vue"
import {usecounterstore} from "@/store/counter"
import {usechannelstore} from "@/store/channel"
const counterstore = usecounterstore()
const usestore = usechannelstore()
</script><template>
<div><h3>数据:{{ counterstore.count }}</h3><son1></son1><son2></son2><hr><button @click="usestore.getlist">获取数据</button><ul><li v-for="item in usestore.channellist" :key="item.id">{{ item.name }}</li></ul>
</div>
</template>

storeToRefs

用于将 Pinia store 实例中的状态属性转换为 ref 对象。

import { defineStore } from 'pinia';const useMyStore = defineStore({id: 'myStore',state: () => ({count: 0,text: 'Hello, Pinia!',}),
});// 在组件中使用 storeToRefs 将状态转换为 ref 对象
const myStore = useMyStore();
const { count, text } = pinia.storeToRefs(myStore);

Pinia持久化

1.安装插件 pinia-plugin-persistedstate

npm i pinia-plugin-persistedstate

2.main.js使用

import persist from 'pinia-plugin-persistedstate'

...

app.use(createPinia().use(persist))

import './assets/main.css'import persist from 'pinia-plugin-persistedstate'
import { createApp } from 'vue'
import {createPinia} from 'pinia'
import App from './App.vue'const pinia = createPinia()
const app = createApp(App)
app.use(pinia.use(persist))
app.mount('#app')

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

import { defineStore } from 'pinia'
import { ref,computed } from 'vue'export const usecounterstore = defineStore('counter',()=>{// 声明数据stateconst count = ref(100)// 声明操作数据的方法active(普通函数)const addcount = ()=>count.value++const subcount = ()=>count.value--//声明基于数据派生的计算属性getters(computed) const double = computed(() => count.value*2)return {count,addcount,subcount,double}
},{persist:true
})

详细见配置 | pinia-plugin-persistedstate (prazdevs.github.io)

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

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

相关文章

代理IP是否会导致网络连接变慢?

目录 一、代理IP的工作原理及其在网络中的作用 二、代理IP可能导致网络连接变慢的因素 三、案例分析 四、优化代理IP使用的建议 五、总结 在网络世界中&#xff0c;代理IP的使用非常普遍&#xff0c;尤其是在需要隐藏真实IP地址、访问受限资源或进行网络爬虫等场景下。然而…

4. Linux文件属性和目录系列

在 Linux 系统中,文件和目录是基本的文件系统组成部分。文件系统是用于组织和存储文件的一种结构,而文件和目录则是文件系统的核心元素。以下是对 Linux 文件和目录的详细解释: 1. 文件(File) 在 Linux 中,文件是数据的集合,可以是文本文件、二进制文件、设备文件等。…

1362:家庭问题(family)

【算法分析】 搜索 从每个顶点尝试开始搜索&#xff0c;如果成功开始进行一次搜索&#xff0c;即可标记整个连通分量。成功开始搜索的次数即为连通分量的个数。搜索过程中对这一趟搜索到的顶点做计数&#xff0c;能达到在最大计数即为顶点数量最多的连通分量的顶点数。…

如何查看mnist数据集的图片

import numpy as np import matplotlib.pyplot as pltdef read_mnist_images(filename):with open(filename, rb) as f:# 读取魔术数字、图像数量、行数、列数magic_number int.from_bytes(f.read(4), big)number_of_images int.from_bytes(f.read(4), big)rows int.from_by…

UE4案例记录

UE4案例记录&#xff08;制作3D角色显示在UI中&#xff09; 制作3D角色显示在UI中 转载自youtube视频 https://www.youtube.com/channel/UCC8f6SxKJElVvaRb7nF4Axg 新建项目 创建一个Actor 场景组件->摄像机组件->场景捕获组件2D&#xff0c;之后添加一个骨骼网格体…

CLion 配置 Qt 开发环境

文章目录 CLion 配置 Qt 开发环境环境说明基本配置1. 创建Qt项目2. 设置CLion工具链3. 配置外部工具 一些问题的补充 CLion 配置 Qt 开发环境 环境说明 操作系统&#xff1a;Windows 10 CLion版本&#xff1a;2023.3.4 CMake版本&#xff1a;3.27.7 Qt6版本&#xff1a;6.6…

Java特性之设计模式【组合模式】

一、组合模式 概述 组合模式&#xff08;Composite Pattern&#xff09;&#xff0c;又叫部分整体模式&#xff0c;是用于把一组相似的对象当作一个单一的对象。组合模式依据树形结构来组合对象&#xff0c;用来表示部分以及整体层次。这种类型的设计模式属于结构型模式&#x…

AHU 汇编 实验一

一、实验名称&#xff1a;实验1 实验1 用Debug命令查看寄存器和内存中的内容 实验目的:求掌握使用Debug命令查看寄存器和内存的方法。 通过第2章两个简单实例认识汇编语言程序&#xff0c;初步了解程序格式&#xff1b;段定义&#xff1b;标号&#xff1b;DOS系统功能&#xf…

基于恒功率PQ控制的三电平并网逆变器MATLAB仿真模型

微❤关注“电气仔推送”获得资料&#xff08;专享优惠&#xff09; 模型简介 三相 T 型三电平逆变器电路如图所示&#xff0c;逆变器主回路由三个单相 T 型逆变器组成。 直流侧输入电压为 UPV&#xff0c;直流侧中点电位 O 设为零电位&#xff0c;交流侧输出侧是三相三线制连…

如何深度学习

信息爆炸时代&#xff0c;诞生了很多新的学习方式&#xff0c;非常轻松就能掌握知识&#xff0c;比如&#xff0c;每天听一本书&#xff0c;半个小时就能学习一本书的精华&#xff0c;比如订阅名家专栏或者课程&#xff0c;在不长的时间内内就能学到很多知识。 很多人认为这样…

ADC不同类型以及原理

对逐次逼近型&#xff08;SAR&#xff09;的理解&#xff1a; 对于我们做技术的而言&#xff0c;用查表法来通俗解释更合适。只是为了提高查表的速度&#xff0c;这个表格不是我们常规的计算温度的时候&#xff0c;表头温度下限&#xff0c;表尾温度上限&#xff0c;而是一上来…

SkiROS2:技能型机器人控制平台的探索之旅

文章目录 引言背景介绍SkiROS2架构实际使用案例1. 在仓库中执行物品搬运任务技能定义行为树构建代码实现 2. 家庭服务机器人技能定义行为树构建代码实现 展望&#xff1a;SkiROS2与大模型技术的结合融合大模型的决策制定情境感知与自适应技能持续学习与技能改进挑战与机遇 结论…

接口隔离原则的实现方法及具体应用

文章目录 一、接口的设计原则二、接口隔离的原则三、实现口隔离原则的方法四、隔离原则的示例代码 一、接口的设计原则 接口应该尽可能地小&#xff0c;尽量只包含一个功能模块所需的方法。这样可以避免接口的臃肿和不必要的依赖关系&#xff0c;提高代码的灵活性和可维护性。 …

【数据结构取经之路】快速排序的非递归实现

概述 递归实现快速排序在一些场景下有栈溢出的风险&#xff0c;下面就谈谈如何用非递归的方法实现快速排序。 非递归实现的思想 递归实现与非递归实现快速排序的本质是一致的&#xff0c;效率并不会因为用了非递归实现而有所提升。递归实现快速排序的本质就在于通过递归&…

电脑音频显示红叉怎么办?这里提供四种方法

前言 如果你在系统托盘中看到音量图标上的红色X,则表示你无法使用音频设备。即使音频设备未被禁用,当你运行音频设备疑难解答时,仍然会看到此错误。 你的电脑将显示已安装高清音频设备,但当你将鼠标悬停在图标上时,它将显示未安装音频输出设备。这是一个非常奇怪的问题,…

Linux系统目录结构详细介绍

目录 一、根目录&#xff08;/&#xff09; 二、/bin 三、/boot 四、/dev 1.设备文件类型&#xff1a; 2.常见设备文件&#xff1a; 五、/etc 六、/home 七、/root 八、/run 九、/sbin 十、 /tmp 十一、/usr 十二、/var Linux系统目录结构是一种层次化的文件系…

leetcode 热题 100_两数相加

题解一&#xff1a; 迭代&#xff1a;首先判断整数0&#xff0c;然后分别遍历两段链表&#xff0c;将对应位数的值相加并存入新链表&#xff0c;再遍历新链表&#xff0c;将节点值val>10的减10&#xff0c;并且其下一节点值val1。需要注意最后一位节点进位是将下一位节点值设…

spring-boot-maven-plugin springboot打包配置问题

目录 一、打包可执行jar 二、打包非可执行jar 三、两种jar对比 springboot项目的pom文件中一般都配置了spring-boot-maven-plugin打包插件。 <!-- 打包插件依赖 --><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-b…

Python逆向:pyc字节码转py文件

一、 工具准备 反编译工具&#xff1a;pycdc.exe 十六进制编辑器&#xff1a;010editor 二、字节码文件转换 在CTF中&#xff0c;有时候会得到一串十六进制文件&#xff0c;通过010editor使用查看后&#xff0c;怀疑可能是python的字节码文件。 三、逆向反编译 将010editor得到…

9、组合模式(结构性模式)

组合模式又叫部分整体模式&#xff0c;它创建了对象组的树形结构&#xff0c;将对象组合成树状结构&#xff0c;以一致的方式处理叶子对象以及组合对象&#xff0c;不以层次高低定义类&#xff0c;都是结点类 一、传统组合模式 举例&#xff0c;大学、学院、系&#xff0c;它们…