【学Vue就跟玩一样】如何使用集中式状态管理的Vuex以及如何模块化编码+命名空间

1.vuex是什么

一个专门在Vue中实现集中式状态管理的一个Vue插件,可以对vue应用中多个组件的共享状态进行集中式的管理(读取/写入),也是一种组件间通信的方式,并且适用于任意组件间通信

2.什么时候使用Vuex

1.多个组件依赖于同一状态

2.来自不同组件的行为需要变更同一状态

1.1如何使用Vuex

首先我们要知道,如果使用了Vuex就大概率需要两个或者多个组件共享一套数据/状态,所以首先需要准备两个组件(分别为Count,Person),再就是我们要在src目录下添加一个store文件,因为Vuex就是依靠store来进行一系列的准备任务的

1.2Count组件

在这个组件内我们可以看到map...一堆东西,这里我们就不得不说vuex里面的四个map了,如何使用map方法我放到了最后,这里我们只介绍一下该组件的功能Count是个有着“强大”计算功能的组件,它可以进行将最后的数进行放大10倍,可以奇数运算,可以延迟运算可谓是极其的“强大”

<template>
  <div>
    <h3>当前和为:{{sum}}</h3>
    <h3>当前和为:放大10倍:{{bigSum}}</h3>
    <h3>我在{{school}},学习{{subject}}</h3>
    <h3>下方组件的总人数{{personList.length}}</h3>

    <select v-model.number="num">
      <option value="1">1</option>
      <option value="2">2</option>
      <option value="3">3</option>
    </select>
    <button @click="increment(num)">+</button>
    <button @click="decrement(num)">-</button>
    <button @click="incrementOdd(num)">奇数+</button>
    <button @click="incrementWait(num)">500ms后再+</button>
  </div>
</template>
<script>
// 引入mapState等
import { mapState, mapGetters, mapMutations, mapActions } from "vuex";
export default {
  name: "Count",
  data() {
    return {
      num: 1 // 用户选择的数字
    };
  },
  computed: {
    // 使用mapState生成计算属性,从state种读取数据(...mapstate()的意思是将其内的对象全部展开的计算属性里面)
    // ...mapState({ sum: "sum", school: "school", subject: "subject" }), // 对象写法
    ...mapState(["sum", "school", "subject", "personList"]), // 数组写法
    // 使用mapGetters生成计算属性,从getters种读取数据
    // ...mapGetters(["bigSum"]), // 数组写法
    ...mapGetters({ bigSum: "bigSum" }) // 数组写法
  },
  methods: {
    // 借助mapMutations生成对应的方法,方法种会调用相应的commit去联系mutations
    ...mapMutations({ increment: "JIA", decrement: "JIAN" }), // 对象式
    ...mapActions({ incrementOdd: "jiaodd", incrementWait: "jiaWait" }) //数组式
    // ...mapActions(["jiaodd", "jiaWait"]) //数组式简写
  },
  mounted() {
  }
};
</script>
<style>
button {
  margin-left: 5px;
}
</style>

1.3Person组件

Person组件有着“强大”的人员添加的功能,他可以按照自己的意愿进行添加你的亲朋好友等

<template>
  <div>
    <h3>人员列表</h3>
    <h3>Count组件的求和为{{sum}}</h3>
    <input type="text" placehodler="请输入名字" v-model="name">
    <button @click="add">添加</button>
    <ul>
      <li v-for="p in personList" :key="p.id">{{p.name}}</li>
    </ul>
  </div>
</template>
<script>
import { nanoid } from "nanoid";
export default {
  name: "Person",
  data() {
    return {
      name: ""
    };
  },
  computed: {
    personList() {
      return this.$store.state.personList;
    },
    sum() {
      return this.$store.state.sum;
    }
  },
  methods: {
    add() {
      const personObj = { id: nanoid(), name: this.name };
      this.$store.commit("ADD_PERSON", personObj);
      this.name = "";
    }
  }
};
</script>

1.4引入组件

分别再App内引入这两个组件

<template>
  <div class="container">
    <Count></Count>
    <Person/>
  </div>
</template>

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

1.5配置store文件夹下的index.js

要在store文件夹下面新建一个index.js文件,然后再index文件里面进行写入如下代码,首先是引入vue和vuex,再使用action进行动作响应,在这里我们可以接收到两个参数分别式contextvalue他们分别式上下文和所传入的值,我们可以再context身上发现我们所配置的state里面的所有东西,这就是context身上的东西,和value,这里value的值就是1

// 创建VUex种的store核心
import Vue from 'vue'
// 引入Vuex
import Vuex from 'vuex'
// 使用vuex插件
Vue.use(Vuex)
// 准备actions——用于组件内的动作响应
const actions = {
    // 奇数加法
    jiaodd(context, value) {
        if (context.state.sum % 2) {
            context.commit('JIA', value)
        }
    },
    // 延迟加
    jiaWait(context, value) {
        setTimeout(() => {
            context.commit("JIA", value)
        }, 500);
    },
}
// 准备mutations——用于数据操作
const mutations = {
    JIA(state, value) {
        state.sum += value
    },
    JIAN(state, value) {
        state.sum -= value
    },
    ADD_PERSON(state, value) {
        console.log('mustations种的ADD_PERSON被调用',state.personList);
        state.personList.unshift(value)
    }
}
// 准备state——用于数据的储存
const state = {
    sum: 0, // 当前和
    school: '山鱼小学',
    subject: '前端',
    personList:[{id:'001',name:'张三'}]
}
// 用于加工state种的数据
const getters = {
    bigSum(state) {
        return state.sum * 10
    }
}
// 创建store并且暴露store
export default new Vuex.Store({
    // actions: actions,// 前后名称一样所以可以触发简写模式
    actions,
    mutations,
    state,
    getters
});

3.四个map方法的使用

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

computed: {
    // 使用mapState生成计算属性,从state种读取数据(...mapstate({})的意思是将其内的对象全部展开的计算属性里面)
    ...mapState({ sum: "sum", school: "school", subject: "subject" }), // 对象写法
        
    // ...mapState(["sum", "school", "subject"]), // 数组写法
  }

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

computed: {
    // 使用mapGetters生成计算属性,从getters种读取数据
    ...mapGetters({bigSum:"bigSum"})
    ...mapGetters(["bigSum"])
  }

3.mapMutations:用于帮助我们生成与mutations交流的方法,包含$store.commit()的函数

methods: {
    // 借助mapMutations生成对应的方法,方法种会调用相应的commit去联系mutations
    ...mapMutations({ increment: "JIA", decrement: "JIAN" }), // 对象式
    // ...mapMutations(["JIA", "JIAN"]), // 数组式(button的名字和vuex里面的名字必须统一)
  },

3.mapActions:用于帮助我们生成与mutations交流的方法,包含$store.commit()的函数

  methods: {
     // 借助mapActions生成对应的方法,方法种会调用相应的dispath去联系actions
    ...mapActions({ incrementOdd: "jiaodd", incrementWait: "jiaWait" }), //对象式
    // ...mapActions(["jiaodd", "jiaWait"]) //数组式
  },

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

4.模块化编码+命名空间

小a:“为啥要开启这个捏?”山鱼:“当然是让代码更好维护,让多种数据分类更加明确。”

小a:“那如何才能做到模块化编码+命名空间呢”

山鱼:“只需要这样即可”

    namespaced: true

将Count组件和Person组件里面的东西全部放到store里面

// Count的相关配置
export default {
    namespaced: true,
    actions: {
        // 奇数加法
        jiaodd(context, value) {
            if (context.state.sum % 2) {
                context.commit('JIA', value)
            }
        },
        // 延迟加
        jiaWait(context, value) {
            setTimeout(() => {
                context.commit("JIA", value)
            }, 500);
        },
    },
    mutations: {
        JIA(state, value) {
            state.sum += value
        },
        JIAN(state, value) {
            state.sum -= value
        },
    },
    state: {
        sum: 0, // 当前和
        school: '山鱼小学',
        subject: '前端',
    },
    getters: {
        bigSum(state) {
            return state.sum * 10
        }
    }
}

2.开启命名空间后读取state的数据

  computed: {
     // 自己读取
    personList() {
      returnthis.$store.state.personAbout.personList;
    },
    sum() {
      returnthis.$store.state.countAbout.sum;
    },
  },
  // 借助mapState读取
computed: {
    ...mapState("countAbout", ["sum", "subject", "school"]), 
    ...mapState("personAbout", ["personList"]) 
  },

3.开启命名空间后,组件中读取getters数据

  computed: {
      // 自己读取
    firstName() {
      returnthis.$store.getters["personAbout/firstPersonName"];
    }
  },
  methods: {
    // 借助mapGetters读取
    // 借助mapMutations生成对应的方法,方法种会调用相应的commit去联系mutations
    ...mapMutations('countAbout',{ increment: "JIA", decrement: "JIAN" }), // 对象式
​
    ...mapActions('countAbout',{ incrementOdd: "jiaodd", incrementWait: "jiaWait" }) //对象式
​
  },

4.开启命名空间后,组件中调用dispatch

methods: {
     // 直接dispath
    addWang() {
      constpersonObj= { id: nanoid(), name: this.name };
      this.$store.dispatch("personAbout/addNameWang", personObj);
      this.name="";
    },
  },
//借助mapGetters读取:
  computed: {
    ...mapGetters('countAbout',['bigSum'])
  },
​

5.开启命名空间后,组件中调用commit

methods: {
    // 直接调用
    add() {
      constpersonObj= { id: nanoid(), name: this.name };
      this.$store.commit("personAbout/ADD_PERSON", personObj);
      this.name="";
    },
 }
  methods: {
    // 借助mapMutations生成对应的方法,方法种会调用相应的commit去联系mutations
    ...mapMutations('countAbout',{ increment: "JIA", decrement: "JIAN" }), // 对象式
      },
  }
只能说模块化很香,代码更清晰数据更分明,后期维护也很niue,今天的小a就到这里了
点赞:您的赞赏是我前进的动力! 👍
收藏:您的支持我是创作的源泉! ⭐
评论:您的建议是我改进的良药! ✍
JavaScript专栏: 小嘎鱼学JS
Vue专栏: 小嘎鱼学Vue
山鱼的个人社区:欢迎大家加入我的个人社区—— 山鱼社区

  • 19
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 17
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 17
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Aic山鱼

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值