【Vuex状态管理】Vuex的基本使用;核心概念State、Getters、Mutations、Actions、Modules的基本使用

news/2024/7/10 0:47:42 标签: vue.js, vue, 前端

目录

  • 1_应用状态管理
    • 1.1_状态管理
    • 1.2_复杂的状态管理
    • 1.3_Vuex的状态管理
  • 2_Vuex的基本使用
    • 2.1_安装
    • 2.2_创建Store
    • 2.3_组件中使用store
  • 3_核心概念State
    • 3.1_单一状态树
    • 3.2_组件获取状态
    • 3.3_在setup中使用mapState
  • 4_核心概念Getters
    • 4.1_getters的基本使用
    • 4.2_getters第二个参数
    • 4.3_getters的返回函数
    • 4.4_mapGetters的辅助函数
  • 5_核心概念Mutations
    • 5.1_使用
    • 5.2_Mutation常量类型
    • 5.3_mutation重要原则
  • 6_核心概念Actions
    • 6.1_基本使用
    • 6.2_分发操作
    • 6.3_actions的异步操作
  • 7_核心概念Modules
    • 7.1_module的基本使用
    • 7.2_module的局部状态
    • 7.3_module的命名空间
    • 7.4_module修改或派发根组件

1_应用状态管理

1.1_状态管理

在开发中,应用程序需要处理各种各样的数据,这些数据需要保存在应用程序中的某一个位置,对于这些数据的管理就称之为是 状态管理。

在前面是如何管理自己的状态呢?

  • 在Vue开发中,使用组件化的开发方式;
  • 而在组件中定义data或者在setup中返回使用的数据,这些数据称之为state;
  • 在模块template中可以使用这些数据,模块最终会被渲染成DOM,称之为View;
  • 在模块中会产生一些行为事件,处理这些行为事件时,有可能会修改state,这些行为事件称之为actions;

1.2_复杂的状态管理

JavaScript开发的应用程序,已经变得越来越复杂了:

  • JavaScript需要管理的状态越来越多,越来越复杂;
  • 这些状态包括服务器返回的数据、缓存数据、用户操作产生的数据等等;
  • 也包括一些UI的状态,比如某些元素是否被选中,是否显示加载动效,当前分页;

当的应用遇到多个组件共享状态时,单向数据流的简洁性很容易被破坏:

  • 多个视图依赖于同一状态;
  • 来自不同视图的行为需要变更同一状态;

是否可以通过组件数据的传递来完成呢?

  • 对于一些简单的状态,确实可以通过props的传递或者Provide的方式来共享状态;
  • 但是对于复杂的状态管理来说,显然单纯通过传递和共享的方式是不足以解决问题的,比如兄弟组件如何共享数据呢

1.3_Vuex的状态管理

管理不断变化的state本身是非常困难的:

  • 状态之间相互会存在依赖,一个状态的变化会引起另一个状态的变化,View页面也有可能会引起状态的变化;
  • 当应用程序复杂时,state在什么时候,因为什么原因而发生了变化,发生了怎么样的变化,会变得非常难以控制和追踪;

因此,是否可以考虑将组件的内部状态抽离出来,以一个全局单例的方式来管理呢?

  • 在这种模式下,组件树构成了一个巨大的 “试图View”;
  • 不管在树的哪个位置,任何组件都能获取状态或者触发行为;
  • 通过定义和隔离状态管理中的各个概念,并通过强制性的规则来维护视图和状态间的独立性,的代码边会变得更加结构化和易于维护、跟踪;

这就是Vuex背后的基本思想,它借鉴了Flux、Redux、Elm(纯函数语言,redux有借鉴它的思想);
Vue官方也在推荐使用Pinia进行状态管理,后续学习


参考官网的图
在这里插入图片描述


2_Vuex的基本使用

2.1_安装

npm install


2.2_创建Store

每一个Vuex应用的核心就是store(仓库): store本质上是一个容器,它包含着应用中大部分的状态(state);

Vuex和单纯的全局对象有什么区别?

  • 第一:Vuex的状态存储是响应式的。 当Vue组件从store中读取状态的时候,若store中的状态发生变化,那么相应的组件也会被更新;

  • 第二:不能直接改变store中的状态。

    • 改变store中的状态的唯一途径就显示提交 (commit) mutation;
    • 这样使得可以方便的跟踪每一个状态的变化,从而让能够通过一些工具帮助更好的管理应用的状态;

demo:

(1)在src文件夹下,建立一个新文件夹store,在该文件夹下,一般创建index.js文件,也可根据实际开发创建。

src/store/index.js

import { createStore } from 'vuex'

const store = createStore({
  state: () => ({
    counter: 100
  })
})  

(2)在main.js注册

import { createApp } from 'vue'
import App from './App.vue'
import store from './store'

createApp(App).use(store).mount('#app')

(3)在App.vue中调用

<template>
  <div class="app">
    <!-- store中的counter -->
    <h2>App当前计数: {{ $store.state.counter }}</h2>
  </div>
</template>

2.3_组件中使用store

在组件中使用store,按照如下的方式:

  • 在模板tempte中使用,比如2.2的demo
  • 在options api中使用,比如computed;
  • 在setup中使用;
<template>
  <div class="app">
      <!-- 在模板tempte中使用store -->
    <h2>Home当前计数: {{ $store.state.counter }}</h2>
    <h2>Computed当前计数: {{ storeCounter }}</h2>
    <h2>Setup当前计数: {{ counter }}</h2>
    <button @click="increment">+1</button>
  </div>
</template>

<script>
  export default {
      //在options api中使用,比如computed;
    computed: {
      storeCounter() {
        return this.$store.state.counter
      }
    }
  }
</script>

<!-- 在setup中使用store -->
<script setup>
  import { toRefs } from 'vue'
  import { useStore } from 'vuex'

  const store = useStore()
  const { counter } = toRefs(store.state)
  
  function increment() {
    store.commit("increment")
  }
</script>

3_核心概念State

3.1_单一状态树

Vuex 使用单一状态树:

  • 用一个对象就包含了全部的应用层级的状态;
  • 采用的是SSOT,Single Source of Truth,也可以翻译成单一数据源;

这也意味着,每个应用将仅仅包含一个 store 实例, 单状态树和模块化并不冲突,后面会涉及到module的概念;

单一状态树的优势:

  • 如果状态信息是保存到多个Store对象中的,那么之后的管理和维护等等都会变得特别困难;
  • 所以Vuex也使用了单一状态树来管理应用层级的全部状态;
  • 单一状态树能够让最直接的方式找到某个状态的片段;
  • 而且在之后的维护和调试过程中,也可以非常方便的管理和维护;

3.2_组件获取状态

在前面的demo已知如何在组件中获取状态了。

当然,如果觉得那种方式有点繁琐(表达式过长),可以使用计算属性:

    computed: {
      storeCounter() {
        return this.$store.state.counter
      }
    }

但是,如果有很多个状态都需要获取话,可以使用mapState的辅助函数:

  • mapState的方式一:对象类型;
  • mapState的方式二:数组类型;
  • 也可以使用展开运算符和来原有的computed混合在一起;

3.3_在setup中使用mapState

在setup中如果单个获取状态是非常简单的, 通过useStore拿到store后去获取某个状态即可。

但是如果使用 mapState 如何获取状态?

(1) 默认情况下,Vuex并没有提供非常方便的使用mapState的方式,下面这种方式不建议使用

<template>
  <div class="app">
    <!-- 在模板中直接使用多个状态 -->
    <h2>name: {{ $store.state.name }}</h2>
    <h2>level: {{ $store.state.level }}</h2>
    <h2>avatar: {{ $store.state.avatarURL }}</h2>
  </div>
</template>

<script setup>
  import { computed } from 'vue'
  import { mapState, useStore } from 'vuex'

  // 一步步完成,步骤繁琐
  const { name, level } = mapState(["name", "level"])
  const store = useStore()
  const cName = computed(name.bind({ $store: store }))
  const cLevel = computed(level.bind({ $store: store }))
</script>

(2)这里进行了一个函数的封装,简化步骤

src/hooks/useState.js

import { computed } from 'vue'
import { useStore, mapState } from 'vuex'

export default function useState(mapper) {
  const store = useStore()
  const stateFnsObj = mapState(mapper)
  
  const newState = {}
  Object.keys(stateFnsObj).forEach(key => {
    newState[key] = computed(stateFnsObj[key].bind({ $store: store }))
  })

  return newState
}

使用该函数

<template>
  <div class="app">
    <!-- 在模板中直接使用多个状态 -->
    <h2>name: {{ $store.state.name }}</h2>
    <h2>level: {{ $store.state.level }}</h2>
    <h2>avatar: {{ $store.state.avatarURL }}</h2>
  </div>
</template>

<script setup>
  import useState from "../hooks/useState"
  // 使用useState封装函数
  const { name, level } = useState(["name", "level"])
</script>

(3)更推荐下面的使用方式

<template>
  <div class="app">
    <!-- 在模板中直接使用多个状态 -->
    <h2>name: {{ $store.state.name }}</h2>
    <h2>level: {{ $store.state.level }}</h2>
    <h2>avatar: {{ $store.state.avatarURL }}</h2>
  </div>
</template>

<script setup>
  import { computed, toRefs } from 'vue'
  import { mapState, useStore } from 'vuex'

  // 3.直接对store.state进行解构(推荐)
  const store = useStore()
  const { name, level } = toRefs(store.state)
</script>

4_核心概念Getters

4.1_getters的基本使用

某些属性可能需要经过变化后来使用,这个时候可以使用getters

在这里插入图片描述


4.2_getters第二个参数

getters可以接收第二个参数

  getters: {
    // 2.在该getters属性中, 获取其他的getters
    message(state, getters) {
      return `name:${state.name} level:${state.level} friendTotalAge:${getters.totalAge}`
    }

  }

4.3_getters的返回函数

  getters: {
    // 3.getters是可以返回一个函数的, 调用这个函数可以传入参数(了解)
    getFriendById(state) {
      return function(id) {
        const friend = state.friends.find(item => item.id === id)
        return friend
      }
    }
  }

4.4_mapGetters的辅助函数

可以使用mapGetters的辅助函数

<template>
  <div class="app">
    <h2>doubleCounter: {{ doubleCounter }}</h2>
    <h2>friendsTotalAge: {{ totalAge }}</h2>
    <!-- 根据id获取某一个朋友的信息 -->
    <h2>id-111的朋友信息: {{ getFriendById(111) }}</h2>
    <h2>id-112的朋友信息: {{ getFriendById(112) }}</h2>
  </div>
</template>

<script>
  import { mapGetters } from 'vuex'

  export default {
    computed: {
      ...mapGetters(["doubleCounter", "totalAge"]),
      ...mapGetters(["getFriendById"])
    }
  }
</script>

也可在setup中使用

<template>
  <div class="app">
    <h2>message: {{ message }}</h2>
  </div>
</template>

<script setup>
  import { computed, toRefs } from 'vue';
  import { mapGetters, useStore } from 'vuex'

  const store = useStore()

  // 1.使用mapGetters ,较麻烦
  // const { message: messageFn } = mapGetters(["message"])
  // const message = computed(messageFn.bind({ $store: store }))

  // 2.直接解构, 并且包裹成ref
  // const { message } = toRefs(store.getters)

  // 3.针对某一个getters属性使用computed
  const message = computed(() => store.getters.message)
</script>

5_核心概念Mutations

更改 Vuex 的 store 中的状态的唯一方法是提交 mutation

5.1_使用

在提交mutation的时候,会携带一些数据,这时可以使用参数,注意payload为对象类型

mutation :{
 add(state,payload){
   statte.counter + = payload
 }
}

提交

$store.commit({
  type: "add",
  count: 100
})

5.2_Mutation常量类型

demo:

(1)在mutaition-type.js,定义常量

export const CHANGE_INFO = "changeInfo"

(2)在store使用常量

  mutations: {
      [CHANGE_INFO](state, newInfo) {
      state.level = newInfo.level
      state.name = newInfo.name
    }
  }

(3)在使用的
在这里插入图片描述


5.3_mutation重要原则

一条重要的原则就是,mutation 必须是同步函数

  • 这是因为devtool工具会记录mutation的日记;
  • 每一条mutation被记录,devtools都需要捕捉到前一状态和后一状态的快照;
  • 但是在mutation中执行异步操作,就无法追踪到数据的变化;

6_核心概念Actions

6.1_基本使用

Action类似于mutation,不同在于:

  • Action提交的是mutation,而不是直接变更状态;

  • Action可以包含任意异步操作;

有一个非常重要的参数context:

  • context是一个和store实例均有相同方法和属性的context对象;
  • 所以可以从其中获取到commit方法来提交一个mutation,或者通过 context.state 和 context.getters 来获取 state 和getters;

具体案例参考这篇文章 :https://blog.csdn.net/qq_21980517/article/details/103398686


6.2_分发操作

在这里插入图片描述


6.3_actions的异步操作

Action 通常是异步的,可以通过让action返回Promise,知道 action 什么时候结束,然后,在Promise的then中来处理完成后的操作。

demo:

index.js中,以发送网络请求为例

action{
	fetchHomeMultidataAction(context) {
      // 1.返回Promise, 给Promise设置then
      // fetch("http://123.207.32.32:8000/home/multidata").then(res => {
      //   res.json().then(data => {
      //     console.log(data)
      //   })
      // })
      
      // 2.Promise链式调用
      // fetch("http://123.207.32.32:8000/home/multidata").then(res => {
      //   return res.json()
      // }).then(data => {
      //   console.log(data)
      // })
      return new Promise(async (resolve, reject) => {
        // 3.await/async
        const res = await fetch("http://123.207.32.32:8000/home/multidata")
        const data = await res.json()
        
        // 修改state数据
        context.commit("changeBanners", data.data.banner.list)
        context.commit("changeRecommends", data.data.recommend.list)

        resolve("aaaaa")
      })
    }
 }   

test3.vue

<script setup>
  import { useStore } from 'vuex'
  // 告诉Vuex发起网络请求
  const store = useStore()
  store.dispatch("fetchHomeMultidataAction").then(res => {
    console.log("home中的then被回调:", res)
  })

</script>



7_核心概念Modules

7.1_module的基本使用

Module的理解?

  • 由于使用单一状态树,应用的所有状态会集中到一个比较大的对象,当应用变得非常复杂时,store 对象就有可能变得相当臃肿;
  • 为了解决以上问题,Vuex 允许将 store 分割成模块(module);
  • 每个模块拥有自己的 state、mutation、action、getter、甚至是嵌套子模块
    在这里插入图片描述

7.2_module的局部状态

对于模块内部的 mutation 和 getter,接收的第一个参数是模块的局部状态对象
在这里插入图片描述


7.3_module的命名空间

默认情况下,模块内部的action和mutation仍然是注册在全局的命名空间中的:

  • 这样使得多个模块能够对同一个 action 或 mutation 作出响应;
  • Getter 同样也默认注册在全局命名空间;

如果希望模块具有更高的封装度和复用性,可以添加 namespaced: true 的方式使其成为带命名空间的模块, 当模块被注册后,它的所有 getter、action 及 mutation 都会自动根据模块注册的路径调整命名

demo:counter,js

const counter = {
  namespaced: true, //命令空间
  state: () => ({
    count: 99
  }),
  mutations: {
    incrementCount(state) {
      console.log(state)
      state.count++
    }
  },
  getters: {
    doubleCount(state, getters, rootState) {
      return state.count + rootState.rootCounter
    }
  },
  actions: {
    incrementCountAction(context) {
      context.commit("incrementCount")
    }
  }
}

export default counter

7.4_module修改或派发根组件

在action中修改root中的state,那么有如下的方式
在这里插入图片描述


http://www.niftyadmin.cn/n/4983450.html

相关文章

【day10】驱动

作业&#xff1a; 基于platform实现 添加设备树节点 irq_led{ compatible “hqyj,irq_led”; //用于获取节点 interrupt-parent <&gpiof>; //引用父节点 interrupts <9 0>; //这个节点引入的中断管脚 led1<&gpioe 10 0>; }; 1.驱动端 #include…

Java学习笔记31——字符流

字符流 字符流为什么出现字符流编码表字符串中的编码解码问题字符流写数据的5中方式字符流读数据的两种方式字符流复制Java文件 字符流 为什么出现字符流 汉字的存储如果是GBK编码占用2个字节&#xff0c;如果是UTF-8占用三个字节 用字节流复制文本文件时&#xff0c;文本文…

如何将 PDF 转换为 Word:前 5 个应用程序

必须将 PDF 转换为 Word 才能对其进行编辑和自定义。所以这里有 5 种很棒的方法 PDF 文件被广泛使用&#xff0c;因为它非常稳定且难以更改。这在处理法律合同、财务文件和推荐信等重要文件时尤其重要。但是&#xff0c;有时您可能需要编辑 PDF 文件。最好的方法是使用应用程序…

C#基础知识点记录

目录 课程一、C#基础1.C#编译环境、基础语法2.Winform-后续未学完 课程二、Timothy C#底层讲解一、类成员0常量1字段2属性3索引器5方法5.1值参数&#xff08;创建副本&#xff0c;方法内对值的操作&#xff0c;不会影响原来变量的值&#xff09;5.2引用参数&#xff08;传的是地…

灵魂课程 | 《张遇升 | 怎样获得高质量睡眠》

生活就像一盒巧克力&#xff0c; 结果往往出人意料&#xff01; ——《阿甘正传》 目录 灵魂课程 | 《张遇升 | 怎样获得高质量睡眠》00 | 为什么你知道这么多&#xff0c;还是睡不好&#xff1f;0.1 作者介绍0.2 可能遇到的两类问题0.2.1 第一类&#xff1a;你觉得自己睡的不好…

分享一篇关于如何使用BootstrapVue的入门指南

你想轻松地创建令人惊叹且响应式的在线应用程序吗&#xff1f;使用BootstrapVue&#xff0c;您可以快速创建美观且用户友好的界面。这个开源工具包是基于Vue.js和Bootstrap构建的&#xff0c;非常适合开发现代Web应用程序。本文将介绍其基础知识&#xff0c;让您可以开始使用这…

mysql数据表Table is marked as crashed and should be repaired 的解决办法

错误原因 网上查了一下&#xff0c;错误的产生原因&#xff0c;有网友说是频繁查询和更新XXXX表造成的索引错误&#xff0c;还有说法是Mysql数据库因某种原因而受到了损坏。 【如&#xff1a;数据库服务器突发性断电&#xff0c;在数据表提供服务时对表的源文件进行某种操作都…

如何使用c3p0连接池???

1.首先下载架包。。。&#xff08;下载链接&#xff1a;https://note.youdao.com/ynoteshare/index.html?id61e2cc939390acc9c7e5017907e98044&typenote&_time1693296531722&#xff09; 2.将架包加入项目文件。 创建一个lib目录&#xff0c;将架包复制进去 右键点击l…