欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 文旅 > 文化 > vue入门四-pinia

vue入门四-pinia

2024/10/23 4:17:07 来源:https://blog.csdn.net/breeze21/article/details/142816495  浏览:    关键词:vue入门四-pinia

参考:丁丁的哔哩哔哩

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);},},
})

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com