vue3使用vuex状态管理、pinia状态管理

239 阅读2分钟

Vuex

Vue3,状态管理的各个属性的作用:

  • state:存储应用程序中的状态数据。它可以包含任何类型的数据,包括基本类型、对象、数组等。可以通过commit和dispatch方法来修改state中的数据。
  • getters:允许你基于 store 中的 state 数据进行计算。类似于Vue组件中的计算属性。通过getters,我们可以将store中的状态数据进行加工、过滤、处理后再返回给组件使用,而无需在组件中手动操作state数据。
  • mutations:用于修改store中的状态数据。每个mutation都有一个字符串的类型和一个handler函数。在handler函数中,我们可以进行同步操作来修改state中的数据。需要注意的是,mutations中的函数必须是同步函数,否则会导致状态不可预测。
  • actions:用于处理异步任务以及提交mutations。在actions中,我们可以编写异步代码,例如向后端API发送请求获取数据等操作。然后通过commit方法提交mutation,以更新state中的数据。actions中的函数是可以是异步函数的,因此我们可以在其中执行异步操作。
  • modules:允许我们将store分割成模块,每个模块都有自己的state、mutations、actions、getters等,以便于管理和维护。每个模块都可以有自己的子模块,形成树状结构。

组件中修改数据

  • dispatch:异步操作,数据提交至actions,用于向后台提交数据
  • commit:同步操作,数据提交至mutations,用于登录成功后读取用户信息写到缓存里
import {useStore} from 'vuex'
const store = useStore()
//打开页面修改数据
store.dispatch('方法名','perosn')


注意:

调用mutation里的方法用context.commit(store里)或store.commit(store外) 调用action里的方法用context.dispatch(store里)或store.dispatch(store外)

context相当于state的父级,包含state中的所有属性

pinia

  • 安装与配置 npm install pinia
  • main.js文件导入createPinia函数并将Pinia插件与Vue应用程序绑定
import {createPinia}from 'pinia'
const pinia = createPinia()
app.use(pinia)
  • example[store文件夹下新建dataStore.js文件]
import {defineStore} from 'pinia'
const dataStore = defineStore('data',{
 state:()=>({
  isShow :true
 }),
 getters:{
     getIsShow(){
      return this.isShow
     }
 },
 actions:{
   //同步方法
   setShow(value){
    this.isShow = value
   },
   // 异步方法
   async fetchData(){
    const res = await fetch('http://xxx.com')
   }
 },
})
export default dataStore
  • 使用Pinia,<script setup>
    • 使用import 引入Pinia中的useStore,import {useStore} from 'pinia'
    • 创建useStore对象,const store = useStore('data')
    • onMounted(()=>{store.fetchData})
    • const data = computed(()=>store.setShow())