vue入门四-pinia

ops/2024/10/21 2:05:54/

参考:丁丁的哔哩哔哩

vue3中如何设置状态管理

provide/infect 跨级通信

1. vue2实现

<!-- index.js -->
// 状态集中管理
// 数据实现响应式
// ref reactive--->对象中存储着状态msg,age,counterimport {reactive} from 'vue'
const store={state:reactive({//定义状态msg:"helloworld"}updateMsg: function()	{this.state.msg='你好'}//如何在App组件通过provide提供
export default store
<!-- app.vue --><script>
import Home from"./views/Home.wue"
import store from "./store".// vue3中如何设置状态管理
// provide/inject 跨级通信
export default {!provide:{store,components:{Home }
</script><template><Home />
</template>
<!-- home.vue --><template><div>{{ store.state.msg }}<div/><div> <button @click="updateMsg">改变按钮<button/> <div/>
<template/><script>
export default {inject:['store'],methods:{updateMsg:function(){this.store.updateMsg()}}
}
<script/>

2.vue3实现

<!-- store.js -->
import { reactive } from 'vue'export const store = reactive({count: 0,increment() {this.count++}
})
<!-- ComponentA.vue -->
<script setup>
import { store } from './store.js'
</script><template><button @click="store.increment()">From: {{ store.count }}</button>
</template>

pinia

  1. pinia 使用
<!-- main.js -->import { createApp } from 'vue'
import { createPinia } from 'pinia'
import App from './App.vue'const pinia = createPinia()
const app = createApp(App)app.use(pinia)
app.mount('#app')
  1. Store

Store (如 Pinia) 是一个保存状态和业务逻辑的实体,它承载着全局状态。它有三个概念,state、getter 和 action,我们可以假设这些概念相当于组件中的 data、 computed 和 methods。

  1. 定义store
import { defineStore } from 'pinia'// 第一个参数是你的应用中 Store 的唯一 ID。
// 第二个参数可接受两类值:Setup 函数或 Option 对象。
export const useAlertsStore = defineStore('alerts', {// 其他配置...
})

option store 和 setup store

// options store 返回的是一个函数
const useAgeStore = defineStore('age',{state:() => { // vue2中 data(){ return {} } 防止数据污染return { age: 33 }},getters:{ // 相当于computed 计算属性gettersAge(state){return state.age + 3;}},actions:{// 相当于methodsaddAge(){// this指向对应的store仓库this.age++;}}
})// setup store 返回的是一个函数
export const useCounterStore=defineStore('main',()=>{const counter=ref(30);//stateconst gettersCounter=computed(()=>{//gettersreturn counter.value+5;})function addcounter(){//actionscounter.value++;}return {counter,gettersCounter,addcounten}
})
  1. 使用store
<script setup>
import { useAgeStore } from '@/stores/counter'
// 可以在组件中的任意位置访问 `store` 变量
const store = useAgeStore() // 调用 useAgeStore()(或者使用 setup() 函数,像所有的组件那样) 后,store 实例被创建
</script>
  1. 解构store
// 破坏了响应性
const { counter, gettersCounter, addcounter } = useCounterStore
// 解决响应性丢失,不能解构actions
const { counter, gettersCounter } = storeToRefs(useCounterStore);

state的基本使用

  1. state中的状态
// options store 返回的是一个函数
const useAgeStore = defineStore('age',{state:() => { // 为了完整类型推理,推荐使用箭头函数// 在 Pinia 中,state 被定义为一个返回初始状态的函数。// 这使得 Pinia 可以同时支持服务端和客户端// vue2中 data(){ return {} } 防止数据污染(针对于服务端)return { age: 33, arr:[1,2,3] }}
})
  1. 修改state中的状态
function changeAge(){// 方式一:直接修改ageStore.age++;// 方式二:批量修改 $patch(对象)  推荐使用ageStore.$patch({ age:40,name:"刘四", arr:[...ageStore.arr,4]})// 方式三:批量修改 $patch(函数)  强烈推荐使用ageStore.$patch( (state)=>{state.age = 33;state.name="王五";state.arr.push(5)})// 方式四:逻辑比较复杂的时候,封装actions中函数
}

getters的基本使用

getters:{ // 相当于computed 计算属性// 方式一 有类型推断gettersAge(state){return state.age + 3;}// 方式二 this此处指向的是store实例,不能对返回值自动推导gettersAge(){return this.age + 3;}// 方式三 箭头函数gettersAge: (state)=>{return state.age + 3}// 访问其他的getters,使用this,注意:不能使用箭头函数!!gettersName(state){return this.gettersAge + state.age;}// 向getters传递参数,返回函数的方式接受参数,和普通的函数一样的// 没有缓存的作用// <template> ageStore.gettersAge(10) </template>gettersAge(state){return (data)=>state.age + data;}// 访问其他store中的gettersgettersAge(state){const counterStore = useCounterStore();return state.age + counterStore.getterCounter;}}

actions的基本使用

actions:不能使用箭头函数,一定要使用普通函数

export const useCounterStore = defineStore('main', {state: () => ({count: 0,}),actions: {increment() {this.count++},// 异步函数// 获取其他store中的actionsasync randomizeCounter() {const counterStore = useCounterStore();if(counterStore.login()){console.log(登录成功);// ...其他操作}let res = await axios.get("https://www.fastmock.sit/");console.log(res);},},
})

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

相关文章

使用verilog设计实现FPGA实现的图像直方图均衡化及其仿真

以下是一个使用Verilog实现图像直方图均衡化的基本框架。 ## 一、图像直方图均衡化原理 1. 首先计算图像的直方图,即统计每个灰度值出现的频率。 2. 然后根据直方图计算累积分布函数(CDF)。 3. 最后根据CDF对每个像素的灰度值进行重新映射,以实现直方图均衡化,增强图像对…

华山论剑之Rust的Trait

华山论剑&#xff0c;群雄荟萃&#xff0c;各显神通。武林中人&#xff0c;各有所长&#xff0c;或剑法飘逸&#xff0c;或掌法刚猛&#xff0c;或轻功绝顶。这就好比Rust中的trait&#xff0c;它定义了一种武功套路&#xff0c;而不同的门派、不同的人&#xff0c;可以将这套武…

在redis创建stream消息队列时报错:ERR unknown command ‘xadd‘

控制台报错内容&#xff1a; 原因&#xff1a; 由于Redis版本过低导致&#xff0c;stream流是5.0版本的新特性&#xff0c;此处为3.2.100的版本会出现这个错误&#xff1b;

React 高级阶段学习计划

React 高级阶段学习计划 目标 深入理解React的渲染机制和性能优化。学会代码分割和懒加载。掌握单元测试和集成测试。学习TypeScript与React的结合。 学习内容 性能优化 React.memo React.memo&#xff1a;用于优化函数组件的性能&#xff0c;避免不必要的重新渲染。示例…

Python从0到100(六十四):Python OpenCV-图像运算进阶实战

前言&#xff1a; 零基础学Python&#xff1a;Python从0到100最新最全教程。 想做这件事情很久了&#xff0c;这次我更新了自己所写过的所有博客&#xff0c;汇集成了Python从0到100&#xff0c;共一百节课&#xff0c;帮助大家一个月时间里从零基础到学习Python基础语法、Pyth…

ERP系统是什么?ERP系统如何与数据库对接?

ERP系统的定义 1.企业ERP系统标准的定义来自于其英文原意&#xff0c;即企业资源规划(Enterprise Resource Planning)。企业资源计划系统是一种集成的软件系统&#xff0c;旨在帮助企业管理其资源。它可以协调各种不同的业务流程&#xff0c;例如供应链管理、采购、库存管理、…

【Flutter】页面布局:层叠布局(Stack、Positioned)

在 Flutter 中&#xff0c;布局系统提供了多种方式来管理 UI 元素的排列方式。其中&#xff0c;Stack 和 Positioned 是非常重要的布局组件&#xff0c;允许开发者将子组件按层叠方式&#xff08;即堆叠&#xff09;布局&#xff0c;使得组件可以相互重叠。通过使用 Stack 和 P…

centos升级g++使其支持c++17

centos升级g使其支持c17 升级g的原因现象原因 升级g方法更新镜像源yum升级g版本 总结 升级g的原因 现象 编译最新版本的jsoncpp报一下错误 jsontest.h:87:37: error: ‘hexfloat’ is not a member of ‘std’oss << std::setprecision(16) << std::hexfloat &l…