Vue学习之--------深入理解Vuex之getters、mapState、mapGetters(2022/9/3)

简介: 这篇文章深入探讨了Vuex中的getters概念和用法,以及如何通过mapState、mapGetters、mapActions和mapMutations四个辅助函数简化组件中的Vuex状态访问和操作,通过实际项目案例展示了这些概念的应用和效果。

这一篇博客的内容是在上一篇博客的基础上进行:深入理解Vuex、原理详解、实战应用

文章目录

  • 1、getters的使用
    • 1.1 概念
    • 1.2 用法
    • 1.3 如何读取数据
  • 2、getters在项目中的实际应用
  • 3、测试效果
  • 4、mapState和mapGetters的引出
    • 4.1 先看之前在组件中取值的方法
    • 4.2 如何优化插值表达式中取值的操作呢?
  • 5、四个map方法的介绍和使用
    • 5.1、mapState方法
    • 5.2、mapGetters方法
    • 5.3 mapActions方法
    • 5.4 mapMutations方法
  • 6、在项目中的实际应用
    • 6.1 项目结构
    • 6.2 store/index.js
    • 6.3 Count.vue
    • 6.4 App.vue
    • 6.5 main.js
  • 7、测试效果(视频展示)

1、getters的使用

1.1 概念

当state中的数据需要经过加工后再使用时,可以使用getters加工。

1.2 用法

store.js中追加getters配置

   const getters = {
       bigSum(state){
           return state.sum * 10
       }
   }

   //创建并暴露store
   export default new Vuex.Store({
       ......
       getters
   })

1.3 如何读取数据

组件中读取数据:$store.getters.bigSum

2、getters在项目中的实际应用

在这里插入图片描述在这里插入图片描述

3、测试效果

在这里插入图片描述

4、mapState和mapGetters的引出

4.1 先看之前在组件中取值的方法

在这里插入图片描述

4.2 如何优化插值表达式中取值的操作呢?

可以在computed中进行设置,这样插值表达式的内容就可以简写
在这里插入图片描述

5、四个map方法的介绍和使用

5.1、mapState方法

用于帮助我们映射state中的数据为计算属性

  • 用法:
   computed: {
       //借助mapState生成计算属性:sum、school、subject(对象写法)
        ...mapState({sum:'sum',school:'school',subject:'subject'}),

       //借助mapState生成计算属性:sum、school、subject(数组写法)
       ...mapState(['sum','school','subject']),
   },

5.2、mapGetters方法

用于帮助我们映射getters中的数据为计算属性

  • 用法:
   computed: {
       //借助mapGetters生成计算属性:bigSum(对象写法)
       ...mapGetters({bigSum:'bigSum'}),

       //借助mapGetters生成计算属性:bigSum(数组写法)
       ...mapGetters(['bigSum'])
   },

5.3 mapActions方法

用于帮助我们生成与actions对话的方法,即:包含$store.dispatch(xxx)的函数

   methods:{
       //靠mapActions生成:incrementOdd、incrementWait(对象形式)
       ...mapActions({incrementOdd:'jiaOdd',incrementWait:'jiaWait'})

       //靠mapActions生成:incrementOdd、incrementWait(数组形式)
       ...mapActions(['jiaOdd','jiaWait'])
   }

5.4 mapMutations方法

用于帮助我们生成与mutations对话的方法,即:包含$store.commit(xxx)的函数

  • 用法
   methods:{
       //靠mapActions生成:increment、decrement(对象形式)
       ...mapMutations({increment:'JIA',decrement:'JIAN'}),

       //靠mapMutations生成:JIA、JIAN(对象形式)
       ...mapMutations(['JIA','JIAN']),
   }

备注:mapActions与mapMutations使用时,若需要传递参数需要:在模板中绑定事件时传递好参数,否则参数是事件对象。

6、在项目中的实际应用

6.1 项目结构

在这里插入图片描述

6.2 store/index.js

//该文件用于创建Vuex中最为核心的store

//引入Vuex
import Vuex from 'vuex'
//引入Vue
import Vue from 'vue'

//使用插件
Vue.use(Vuex)

//准备action-- 用于响应组件中的动作
const actions = {
    jia(context, value) {
        context.commit('JIA', value)
    },

    jiaOdd(context, value) {
        if (context.state.sum % 2) {
            context.commit('JIA', value)
        }
    },

    jiaWait(context, value) {
        setTimeout(() => {
            context.commit('JIA', value)
        }, 500);
    }
}

//准备mutations-- 用于操作数据(state)
const mutations = {
    JIA(state, value) {
        state.sum += value

    },

    JIAN(state, value) {
        state.sum -= value

    }

}

//准备state--用于存储数据
const state = {
    sum: 0,//当前的和,
    name: '张三',
    address: "广州"
}

//准备getters
const getters = {
    bigSum(state) {
        return state.sum * 10
    }
}

//第一种形式
//创建并且暴露store
export default new Vuex.Store({
    actions,
    mutations,
    state,
    getters,
})

//第二种形式

// //创建store
// const store = new Vuex.Store({
//     actions,
//     mutations,
//     state,
// })

// //导出store
// export default store

6.3 Count.vue

实际上就是简化代码的操作、之前原始写法保留、比较参考

<template>
  <div>
    <h1>当前求和为:{
  
  { sum }}</h1>
    <h2>当前求和扩大十倍为:{
  
  { bigSum }}</h2>
    <h3>你好,{
  
  { name }}在{
  
  { address }}工作</h3>
    <select v-model.number="n">
      <option value="1">1</option>
      <option value="2">2</option>
      <option value="3">3</option>
    </select>
    <button @click="increment(n)">+</button>
    <button @click="decrement(n)">-</button>
    <button @click="incrementOdd(n)">当前求和为奇数再加</button>
    <button @click="incrementWait(n)">等一等再加</button>
  </div>
</template>

<script>
import { mapState, mapGetters, mapActions, mapMutations } from "vuex";
export default {
  name: "Count",
  data() {
    return {
      n: 1, //用户选择的数字
    };
  },
  methods: {
    /* 自己亲自写的方法
     decrement() {
      this.$store.commit("JIAN", this.n);
    },
    increment() {
      this.$store.commit("jia", this.n);
    },

    */
    //借助mapMutations生成对应的方法,方法中会调用commit去联系mutations(对象写法)
    ...mapMutations({ increment: "JIA", decrement: "JIAN" }),

    //借助mapMutations生成对应的方法,方法中会调用commit去联系mutations(数组写法)。方法的调用要改写为JIA(n)
    // ...mapMutations(['JIA','JIAN

    /*
    incrementOdd() {
      this.$store.dispatch("jiaodd", this.n);
    },
    incrementWait() {
      this.$store.dispatch("jiaWait", this.n);
    },
  */
    //借助mapActions生成对应的方法,方法中会调用dispatch去联系actions(对象写法)
    ...mapActions({ incrementOdd: "jiaOdd", incrementWait: "jiaWait" }),

    //借助mapActions生成对应的方法,方法中会调用dispatch去联系actions(数组写法)
    // ...mapActions(['jiaOdd','jiaWait'])
  },
  computed: {
    /* 自己写计算属性
    sum() {
      return this.$store.state.sum;
    },
    name() {
      return this.$store.state.name;
    },
    address() {
      return this.$store.state.address;
    },

    */

    //  借助mapState生成计算属性,从state中读取数据(对象写法)
    // ...mapState({he:'sum',xingming:'name',dizhi:'address'}),
    //数组写法
    ...mapState(["sum", "name", "address"]),

    // bigSum() {
    //   return this.$store.getters.bigSum;
    // },

    //借助mapGatters生成计算属性,从getters中读取数据,(对象写法)
    // ...mapGetters({bigSum:'bigSum'})
    //数组写法
    ...mapGetters(["bigSum"]),
  },
};
</script>

<style lang="css">
button {
  margin-left: 5px;
}
</style>

6.4 App.vue

<template>
    <div>
        <Count/>
    </div>
</template>

<script>
    import Count from './components/Count'
    export default {
        name:'App',
        components:{Count},
    }
</script>

6.5 main.js

// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'

//引入store
import store from './store/index.js'

Vue.config.productionTip = false

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  store,
  render: h => h(App),
  beforenCreate() {
    Vue.prototype.$bus = this
  }

})

7、测试效果(视频展示)

vuex

相关文章
|
5月前
|
JavaScript
Vue中如何实现兄弟组件之间的通信
在Vue中,兄弟组件可通过父组件中转、事件总线、Vuex/Pinia或provide/inject实现通信。小型项目推荐父组件中转或事件总线,大型项目建议使用Pinia等状态管理工具,确保数据流清晰可控,避免内存泄漏。
506 2
|
4月前
|
缓存 JavaScript
vue中的keep-alive问题(2)
vue中的keep-alive问题(2)
427 137
|
8月前
|
人工智能 JavaScript 算法
Vue 中 key 属性的深入解析:改变 key 导致组件销毁与重建
Vue 中 key 属性的深入解析:改变 key 导致组件销毁与重建
976 0
|
7月前
|
人工智能 JSON JavaScript
VTJ.PRO 首发 MasterGo 设计智能识别引擎,秒级生成 Vue 代码
VTJ.PRO发布「AI MasterGo设计稿识别引擎」,成为全球首个支持解析MasterGo原生JSON文件并自动生成Vue组件的AI工具。通过双引擎架构,实现设计到代码全流程自动化,效率提升300%,助力企业降本增效,引领“设计即生产”新时代。
564 1
|
7月前
|
JavaScript 安全
在 Vue 中,如何在回调函数中正确使用 this?
在 Vue 中,如何在回调函数中正确使用 this?
390 0
|
JavaScript
vue状态管理vuex
Vuex就是提供一个仓库,Store仓库里面放了很多对象。其中state就是数据源存放地,对应于与一般Vue对象里面的data(后面讲到的actions和mutations对应于methods)。 在使用Vuex的时候通常会创建Store实例new Vuex.
1399 0
|
10月前
|
JavaScript
vue实现任务周期cron表达式选择组件
vue实现任务周期cron表达式选择组件
1214 4
|
8月前
|
JavaScript UED
用组件懒加载优化Vue应用性能
用组件懒加载优化Vue应用性能
|
9月前
|
JavaScript 数据可视化 前端开发
基于 Vue 与 D3 的可拖拽拓扑图技术方案及应用案例解析
本文介绍了基于Vue和D3实现可拖拽拓扑图的技术方案与应用实例。通过Vue构建用户界面和交互逻辑,结合D3强大的数据可视化能力,实现了力导向布局、节点拖拽、交互事件等功能。文章详细讲解了数据模型设计、拖拽功能实现、组件封装及高级扩展(如节点类型定制、连接样式优化等),并提供了性能优化方案以应对大数据量场景。最终,展示了基础网络拓扑、实时更新拓扑等应用实例,为开发者提供了一套完整的实现思路和实践经验。
1245 78
|
10月前
|
缓存 JavaScript 前端开发
Vue 基础语法介绍
Vue 基础语法介绍