Vuex的状态管理

本文整理来自 深入Vue3+TypeScript技术栈-coderwhy大神新课 ,只作为个人笔记记录使用,请大家多支持王红元老师。

什么是状态管理

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

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

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

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

    当我们的应用遇到多个组件共享状态时,单向数据流的简洁性很容易被破坏,因为多个视图依赖于同一状态,来自不同视图的行为需要变更同一状态。

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

    Vuex的状态管理

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

    因此,我们是否可以考虑将组件的内部状态抽离出来,以一个全局单例的方式来管理呢?
    在这种模式下,我们的组件树构成了一个巨大的 “视图View”,不管在树的哪个位置,任何组件都能获取状态或者触发行为,通过定义和隔离状态管理中的各个概念,并通过强制性的规则来维护视图和状态间的独立性,我们的代码边会变得更加结构化和易于维护、跟踪。

    这就是Vuex背后的基本思想,它借鉴了Flux、Redux、Elm(纯函数语言,redux有借鉴它的思想)。

    Vuex有五大核心: state getters mutations actions modules ,下面我们慢慢讲。

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

    Vuex和单纯的全局对象有什么区别呢?
    第一:Vuex的状态存储是响应式的。当Vue组件从store中读取状态的时候,若store中的状态发生变化,那么相应的组件也会被更新。
    第二:你不能直接改变store中的状态。改变store中的状态的唯一途径就是提交 (commit) mutation,这样使得我们可以方便的跟踪每一个状态的变化,从而让我们能够通过一些工具帮助我们更好的管理应用的状态。

    使用步骤:
    ① 创建Store对象;
    ② 在app中通过插件安装;

    组件中使用store

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

  • 在模板中使用;
  • 在options api中使用,比如computed;
  • 在setup中使用;
  • Vue devtool

    vue其实提供了一个devtools,方便我们对组件或者vuex进行调试。我们需要安装beta版本支持vue3,目前是6.0.0 beta15。

    有两种常见的安装方式:
    方式一:通过chrome的商店;
    方式二:手动下载代码,编译、安装;

    由于某些原因我们可能不能正常登录Chrome商店,所以可以选择第二种;

    https://github.com/vuejs/devtools/tree/v6.0.0-beta.15 下载代码;
  • 打开项目,终端执行 yarn install 安装相关的依赖;
  • 终端执行 yarn run build 打包;
  • 打开浏览器,点击加载已解压的扩展程序;
  • 单一状态树

    Vuex 使用单一状态树,用一个对象就包含了全部的应用层级的状态,采用的是SSOT,Single Source of Truth,也可以翻译成单一数据源,这也意味着,每个应用将仅仅包含一个 store 实例,单状态树和模块化并不冲突,后面我们会讲到module的概念。

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

    Vuex的简单使用

    和使用vue-router一样,我们需要创建一个store文件夹,然后在store文件夹里创建一个index.js文件,在index.js文件里面将store对象导出。然后在main.js文件里面使用store。

    main.js文件代码如下:

    import { createApp } from 'vue'
    import App from './App.vue'
    //导入创建的store
    import store from './store'
    //使用store
    createApp(App).use(store).mount('#app')
    

    index.js代码如下:

    import { createStore } from "vuex"
    const store = createStore({
      // 保存的数据
      // state是个函数,返回一个对象,和data类似
      // 以前是个对象,现在我们推荐写成一个函数
      state() {
        return {
          counter: 100,
          name: "why", 
          age: 18,
          height: 1.88
      // 对数据进行一些加工
      getters: {
        doubleCounter(state) {
          return state.counter * 2
      //修改数据
      mutations: {
        increment(state) {
          state.counter++
    export default store;
    

    使用数据和修改数据:

    //使用vuex中的数据
    <h2>App:{{ $store.state.counter }}</h2>
    //通过commit调用mutations中的increment方法,从而修改数据
    this.$store.commit("increment")
    

    获取组件状态:state

    在前面我们已经学习过如何在组件中获取状态了,当然,如果觉得那种方式有点繁琐(表达式过长),我们可以使用计算属性。

    但是,如果我们有很多个状态都需要获取话,一个一个写计算属性会很麻烦,我们可以使用mapState辅助函数。mapState接收的参数可以是数组类型或者对象类型。我们也可以使用展开运算符和来原有的computed混合在一起。

    在computed中使用mapState

    <template>
        <h2>Home:{{ $store.state.counter }}</h2>
        <h2>Home:{{ sCounter }}</h2>
        <h2>Home:{{ sName }}</h2>
        <!-- <h2>Home:{{ age }}</h2>
        <h2>Home:{{ height }}</h2> -->
    </template>
    <script>
      import { mapState } from 'vuex'
      export default {
        computed: {
          fullName() {
            return "Kobe Bryant"
          // 其他的计算属性, 从state获取,会自动映射成计算属性
          // ...mapState(["counter", "name", "age", "height"])
          // 传入对象可以重命名
          ...mapState({
            sCounter: state => state.counter,
            sName: state => state.name
    </script>
    <style scoped>
    </style>
    

    在setup中使用mapState

    在setup中如果我们单个获取状态是非常简单的,通过useStore拿到store后去获取某个状态即可,但是如果我们需要使用 mapState 的功能呢?

    <template>
        <h2>Home:{{ $store.state.counter }}</h2>
        <h2>{{sCounter}}</h2>
        <h2>{{counter}}</h2>
        <h2>{{name}}</h2>
        <h2>{{age}}</h2>
        <h2>{{height}}</h2>
    </template>
    <script>
      import { mapState, useStore } from 'vuex'
      import { computed } from 'vue'
      export default {
        computed: {
          fullName: function() {
            return "1fdasfdasfad"
          ...mapState(["name", "age"])
        setup() {
          const store = useStore()
          // setup中写成计算属性,这也是常用的方法
          const sCounter = computed(() => store.state.counter)
          // const sName = computed(() => store.state.name)
          // const sAge = computed(() => store.state.age)
          //返回的是函数数组
          const storeStateFns = mapState(["counter", "name", "age", "height"])
          // 我们需要做如下操作,将 {name: function, age: function, height: function} 转成 {name: ref, age: ref, height: ref}
          const storeState = {}
          Object.keys(storeStateFns).forEach(fnKey => {
            // 虽然我们使用的是mapState的方式,vue内部还是会通过this.$store.state获取数据,所以我们给它绑定this
            const fn = storeStateFns[fnKey].bind({$store: store})
            // 将fn用computed包裹一下
            storeState[fnKey] = computed(fn)
          return {
            sCounter,
            ...storeState
    </script>
    <style scoped>
    </style>
    

    默认情况下,在setup中,Vuex并没有提供非常方便的使用mapState的方式,这里我们进行了一个函数的封装,新建useState.js文件,代码如下:

    import { computed } from 'vue'
    import { mapState, useStore } from 'vuex'
    export function useState(mapper) {
      // 拿到store对象
      const store = useStore()
      // 获取到对应的对象的functions: {name: function, age: function}
      const storeStateFns = mapState(mapper)
      // 对数据进行转换
      const storeState = {}
      Object.keys(storeStateFns).forEach(fnKey => {
        const fn = storeStateFns[fnKey].bind({$store: store})
        storeState[fnKey] = computed(fn)
      return storeState
    

    使用useState函数如下:

    <template>
        <h2>Home:{{ $store.state.counter }}</h2>
        <h2>{{counter}}</h2>
        <h2>{{name}}</h2>
        <h2>{{age}}</h2>
        <h2>{{height}}</h2>
        <h2>{{sCounter}}</h2>
        <h2>{{sName}}</h2>
    </template>
    <script>
      //导入函数
      import { useState } from '../hooks/useState'
      export default {
        setup() {
          // useState可以传数组或者对象,这是因为内部的mapState可以传数组或者对象
          const storeState = useState(["counter", "name", "age", "height"])
          const storeState2 = useState({
            sCounter: state => state.counter,
            sName: state => state.name
          return {
            ...storeState,
            ...storeState2
    </script>
    <style scoped>
    </style>
    

    这样我们就使用useState函数实现了原来computed中的mapState函数的功能。

    getters的基本使用

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

    getters: {
      // 第一个参数是state,第二个参数是getters
      // 返回一个值,使用:<h2>总价值: {{ $store.getters.totalPrice }}</h2>
      totalPrice(state, getters) {
        let totalPrice = 0
        for (const book of state.books) {
          totalPrice += book.count * book.price
        //访问另外一个getters
        return totalPrice * getters.currentDiscount
      currentDiscount(state) {
        return state.discount * 0.9
    

    使用如下:

    <h2>总价值: {{ $store.getters.totalPrice }}</h2>
    

    getters第二个参数

    getters可以接收第二个参数,从而实现在getters里面访问另外一个getters,代码如上。

    getters的返回函数

    getters中的函数本身,可以返回一个函数,那么在使用的地方相当于可以调用这个函数:

    getters: {
      //除了返回一个值,还可以返回一个函数
      //使用的时候调用函数,传入参数即可:<h2>总价值: {{ $store.getters.totalPriceCountGreaterN(1) }}</h2>
      totalPriceCountGreaterN(state, getters) {
        return function(n) {
          let totalPrice = 0
          for (const book of state.books) {
            if (book.count > n) {
              totalPrice += book.count * book.price
          return totalPrice * getters.currentDiscount
    

    使用如下:

    <h2>总价值: {{ $store.getters.totalPriceCountGreaterN(3) }}</h2>
    

    getters返回模板字符串

    getters: {
      // 返回模板字符串
      nameInfo(state) {
        return `name: ${state.name}`
      ageInfo(state) {
        return `age: ${state.age}`
      heightInfo(state) {
        return `height: ${state.height}`
    

    mapGetters辅助函数

    和state一样,如果我们感觉通过$store.getters.totalPrice获取getters有点麻烦,可以将其写成计算属性(代码如下),但是如果getters特别多,我们一个一个写计算属性也会很麻烦,所以我们需要mapGetters辅助函数。

    computed: {
      totalPrice() {
        return this.$store.getters.totalPrice
    

    在computed中使用mapGetters

    computed: {
      //传入数组
      ...mapGetters(["nameInfo", "ageInfo", "heightInfo"]),
      //传入对象,重命名
      ...mapGetters({
        //这里和mapState的对象写法不一样,mapState的对象写法是传入一个函数,这里直接传入一个字符串就可以
        sNameInfo: "nameInfo",
        sAgeInfo: "ageInfo"
    

    使用如下:

    <h2>{{ ageInfo }}</h2>
    <h2>{{ heightInfo }}</h2>
    <h2>{{ sNameInfo }}</h2>
    <h2>{{ sAgeInfo }}</h2>
    

    在setup中使用mapGetters

    和mapState一样,在setup中我们可以直接将其写成计算属性,这也是常用的写法:

    setup() {
      const store = useStore()
      // setup中写成计算属性,这也是常用的方法
      const sCounter = computed(() => store.getters.counter)
      // const sName = computed(() => store.getters.name)
      // const sAge = computed(() => store.getters.age)
      return {
        sCounter,
    

    但是如果属性多了,我们就需要写很多的计算属性,所以在setup中使用mapGetters,我们可以封装一个useGetters函数,新建useGetters.js文件,代码如下:

    import { computed } from 'vue'
    import { mapGetters, useStore } from 'vuex'
    export function useGetters(mapper) {
      // 拿到store对象
      const store = useStore()
      // 获取到对应的对象的functions: {name: function, age: function}
      const storeStateFns = mapGetters(mapper)
      // 对数据进行转换
      const storeState = {}
      Object.keys(storeStateFns).forEach(fnKey => {
        const fn = storeStateFns[fnKey].bind({$store: store})
        storeState[fnKey] = computed(fn)
      return storeState
    

    使用如下:

    <template>
        <h2>{{ nameInfo }}</h2>
        <h2>{{ ageInfo }}</h2>
        <h2>{{ heightInfo }}</h2>
    </template>
    <script>
      // 导入函数
      import { useGetters } from '../hooks/useGetters'
      export default {
        computed: {
        setup() {
          //使用useGetters函数
          const storeGetters = useGetters(["nameInfo", "ageInfo", "heightInfo"])
          return {
            ...storeGetters
    </script>
    <style scoped>
    </style>
    

    封装useState.js和useGetters.js

    我们发现useState.js和useGetters.js代码几乎是一样的,所以我们新建useMapper.js文件,重新封装一下,代码如下:

    import { computed } from 'vue'
    import { useStore } from 'vuex'
    //具体是使用mapState还是使用mapGetters我们不清楚,所以让外界传进来mapFn
    export function useMapper(mapper, mapFn) {
      // 拿到store对象
      const store = useStore()
      // 获取到对应的对象的functions: {name: function, age: function}
      const storeStateFns = mapFn(mapper)
      // 对数据进行转换
      const storeState = {}
      Object.keys(storeStateFns).forEach(fnKey => {
        const fn = storeStateFns[fnKey].bind({$store: store})
        storeState[fnKey] = computed(fn)
      return storeState
    

    这时候useState.js代码就是:

    import { mapState } from 'vuex'
    import { useMapper } from './useMapper'
    export function useState(mapper) {
      return useMapper(mapper, mapState)
    

    useGetters.js代码就是:

    import { mapGetters } from 'vuex'
    import { useMapper } from './useMapper'
    export function useGetters (mapper) {
      return useMapper(mapper, mapGetters)
    

    这时候我们只需要新建一个index.js文件作为统一的出口,下次我们使用的时候直接导入这个文件就行了,代码如下:

    import { useGetters } from './useGetters';
    import { useState } from './useState';
    export {
      useGetters,
      useState
    

    Mutations基本使用

    Mutations定义如下:

    mutations: {
      increment(state) {
        state.counter++;
      decrement(state) {
        state.counter--;
      [INCREMENT_N](state, payload) {
        state.counter += payload.n
      addBannerData(state, payload) {
        state.banners = payload
    

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

    <template>
        <h2>当前计数: {{ $store.state.counter }}</h2>
          <!-- 不传参数 -->
          <button @click="$store.commit('increment')">+1</button>
          <button @click="$store.commit('decrement')">-1</button>
         <!-- 传参数 -->
          <button @click="addTen">+10</button>
    </template>
    <script>
      export default {
        methods: {
          addTen() {
            // 传入一个参数
            // this.$store.commit('incrementN', 10)
            // 传入多个参数就写成一个对象
            // this.$store.commit('incrementN', {n: 10, name: "why", age: 18})
            // 这时候后面的参数就会被传到incrementN函数的第二个参数
            // 另外一种提交风格
            this.$store.commit({
              type: 'incrementN',
              n: 10, 
              name: "why", 
              age: 18
    </script>
    <style scoped>
    </style>
    

    Mutation常量类型

    上面代码还有个小问题,就是函数名incrementN容易写错,而且写错之后很难发现,这时候我们可以将函数名incrementN定义成常量。

    在store文件夹中新建mutation-types.js文件,代码如下:

    export const INCREMENT_N = "increment_n"
    

    定义mutation:

    import { INCREMENT_N } from './mutation-types'
    [INCREMENT_N](state, payload) {
      state.counter += payload.n
    

    提交mutation:

    import { INCREMENT_N } from '../store/mutation-types'
    this.$store.commit(INCREMENT_N, 10)
    

    mapMutations辅助函数

    上面代码,直接通过this.$store.commit(INCREMENT_N, 10)调用会很长,封装成一个addTen函数又会多了一个函数,这时候我们可以使用mapMutations辅助函数将我们需要使用的函数映射到methods里面。当我们使用mapMutations映射之后,调用方法,方法内部会调用$store.commit,这样我们就不用写this.$store.commit(INCREMENT_N, 10)这样很长的代码了。

    <template>
        <h2>当前计数: {{ $store.state.counter }}</h2>
          <!-- 当我们使用mapMutations映射之后,调用方法,方法内部会调用$store.commit -->
          <button @click="increment">+1</button>
          <button @click="add">+1</button>
          <button @click="decrement">-1</button>
          <button @click="increment_n({n: 10})">+10</button>
    </template>
    <script>
      import { mapMutations, mapState } from 'vuex'
      import { INCREMENT_N } from '../store/mutation-types'
      export default {
        //在methods中使用
        methods: {
          // 传入数组
          ...mapMutations(["increment", "decrement", INCREMENT_N]),
          // 传入对象,改名字
          ...mapMutations({
            add: "increment"
        setup() {
          // 在setup中使用就比mapState和mapGetters简单多了
          const storeMutations = mapMutations(["increment", "decrement", INCREMENT_N])
          return {
            ...storeMutations
    </script>
    <style scoped>
    </style>
    

    Mutation重要原则

    一条重要的原则:mutation 必须是同步函数,这是因为devtool工具会记录mutation的日记,每一条mutation被记录,devtools都需要捕捉到前一状态和后一状态的快照,但是在mutation中执行异步操作,就无法追踪到数据的变化,所以Vuex的重要原则中要求 mutation 必须是同步函数。

    Actions的基本使用

    Actions类似于Mutations,不同在于:

  • Action提交的是mutation,而不是直接变更状态;
  • Action可以包含任意异步操作;
  • 如果一些网络请求的数据是直接存到Vuex里面,那么网络请求就没必要写到组件中了,直接写到actions中,这样在组件中我们只需要做一次事件派发就行了。

    actions: {
      // 第一个参数是context,第二个参数是我们调用dispatch传递过来的参数{count: 100} 
      incrementAction(context, payload) {
        console.log(payload)
        // 延迟1s
        setTimeout(() => {
          context.commit('increment')
        }, 1000);
      // context的其他属性
      decrementAction({ commit, dispatch, state, rootState, getters, rootGetters }) {
        commit("decrement")
      //如果一些网络请求的数据是直接存到Vuex里面,那么网络请求就没必要写到组件中了,直接写到actions中即可
      getHomeMultidata(context) {
         //返回Promise对象,好在then或者catch里面处理其他事情
         return new Promise((resolve, reject) => {
          axios.get("http://123.207.32.32:8000/home/multidata").then(res => {
            //拿到数据后提交commit
            context.commit("addBannerData", res.data.data.banner.list)
            resolve({name: "coderwhy", age: 18})
          }).catch(err => {
            reject(err)
    

    这里有一个非常重要的参数context,context是一个和store实例均有相同方法和属性的context对象。所以我们可以从其中获取到commit方法来提交一个mutation,或者通过 context.state 和 context.getters 来获取 state 和 getters。但是为什么它不是store对象呢?这个等到我们讲Modules时再具体来说。

    Actions的分发操作

    进行action的分发使用的是 store 上的dispatch函数:

    <template>
        <h2>当前计数: {{ $store.state.counter }}</h2>
          <button @click="increment">+1</button>
          <button @click="decrement">-1</button>
    </template>
    <script>
      import axios from 'axios'
      export default {
        methods: {
          increment() {
            //分发,携带参数
            this.$store.dispatch("incrementAction", {count: 100})
          decrement() {
            //派发风格(对象类型),携带参数
            this.$store.dispatch({
              type: "decrementAction",
              count: 100
        mounted() {
          this.$store.dispatch("getHomeMultidata")
        setup() {
    </script>
    <style scoped>
    </style>
    

    mapActions辅助函数

    和Mutations一样,如果我们不想写this.$store.dispatch("incrementAction", {count: 100})这些代码,可以使用mapActions辅助函数,它也有两种写法:数组类型和对象类型。

    <template>
        <h2>当前计数: {{ $store.state.counter }}</h2>
          <button @click="incrementAction">+1</button>
          <button @click="decrementAction">-1</button>
          <button @click="add">+1</button>
          <button @click="sub">-1</button>
    </template>
    <script>
      import { mapActions } from 'vuex'
      export default {
        // 在methods中使用
        methods: {
          ...mapActions(["incrementAction", "decrementAction"]),
          ...mapActions({
            add: "incrementAction",
            sub: "decrementAction"
        // 在setup中使用
        setup() {
          const actions = mapActions(["incrementAction", "decrementAction"])
          const actions2 = mapActions({
            add: "incrementAction",
            sub: "decrementAction"
          return {
            ...actions,
            ...actions2
    </script>
    <style scoped>
    </style>
    

    Actions的异步操作

    Action 通常是异步的,那么如何知道 Action 什么时候结束呢?
    我们可以通过让Action返回Promise,在Promise的then中来处理完成后的操作。

    actions: {
      getHomeMultidata(context) {
        //返回Promise对象,好在then或者catch里面处理其他事情
        return new Promise((resolve, reject) => {
          axios.get("http://123.207.32.32:8000/home/multidata").then(res => {
            //拿到数据后提交commit
            context.commit("addBannerData", res.data.data.banner.list)
            //回调then
            resolve({name: "coderwhy", age: 18})
          }).catch(err => {
            //回调catch
            reject(err)
    
    <template>
        <h2>当前计数: {{ $store.state.counter }}</h2>
          <button @click="incrementAction">+1</button>
          <button @click="decrementAction">-1</button>
          <button @click="add">+1</button>
          <button @click="sub">-1</button>
    </template>
    <script>
      import { onMounted } from "vue";
      import { useStore } from 'vuex'
      export default {
        setup() {
          const store = useStore()
          onMounted(() => {
            // 派发操作
            const promise = store.dispatch("getHomeMultidata")
            promise.then(res => {
              //请求成功的操作
              console.log(res)
            }).catch(err => {
              //请求失败的操作
              console.log(err)
    </script>
    <style scoped>
    </style>
    

    Module的基本使用

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

    在store文件夹中新建modules文件夹和index.js文件,modules文件夹用于存放模块js文件。

    home.js文件如下:

    const homeModule = {
      state() {
        return {
          homeCounter: 100
      getters: {
      mutations: {
      actions: {
    export default homeModule
    

    user.js文件如下:

    const userModule = {
      state() {
        return {
          userCounter: 10
      getters: {
      mutations: {
      actions: {
    export default userModule
    

    index.js文件代码如下:

    import { createStore } from "vuex"
    // 导入某个模块相关的状态管理
    import home from './modules/home'
    import user from './modules/user'
    const store = createStore({
      // 保存的数据
      state() {
        return {
          rootCounter: 100
      // 对数据进行一些加工
      getters: {
        doubleRootCounter(state) {
          return state.rootCounter * 2
      //修改数据
      mutations: {
        increment(state) {
          state.rootCounter++
      // 状态管理,模块划分
      modules: {
        home,
    export default store;
    

    组件中使用如下:

    <template>
        <h2>{{ $store.state.rootCounter }}</h2>
        <!-- 先获取home模块,再通过home模块拿数据 -->
        <h2>{{ $store.state.home.homeCounter }}</h2>
        <h2>{{ $store.state.user.userCounter }}</h2>
    </template>
    <script>
      export default {
        setup() {
    </script>
    <style scoped>
    </style>
    

    module的命名空间

    先说两个问题:

    问题一:比如index.js里面的mutations内有一个increment方法,home.js里面的mutations内也有一个increment方法,当我们提交commit触发increment方法的时候,这两个increment方法都会被调用。这里有个问题,因为有时候我们不想两个increment方法都被调用。

    问题二:当我们在home.js里面的getters里面定义一个doubleHomeCounter,无论你是通过$store.state.home.doubleHomeCounter还是$store.state.home.getters.doubleHomeCounter还是$store.getters.home.doubleHomeCounter其实都是拿不到doubleHomeCounter,这是因为默认做了个合并,我们需要通过$store.getters.doubleHomeCounter才能拿到doubleHomeCounter。这里有个问题,因为我们不知道doubleHomeCounter到底是哪个模块里面的。

    这是因为,默认情况下,模块内部的mutation和action仍然是注册在全局的命名空间中的,这样使得多个模块能够对同一个mutation或action作出响应,Getters 同样也默认注册在全局命名空间。

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

    当我们加上namespaced: true后,每个模块就是独立的了,我们就要指定是哪个模块,如下:

    <template>
        <!-- 获取根的rootCounter -->
        <h2>root:{{ $store.state.rootCounter }}</h2>
        <!-- 获取home的homeCounter -->
        <h2>home:{{ $store.state.home.homeCounter }}</h2>
        <!-- 获取user的userCounter -->
        <h2>user:{{ $store.state.user.userCounter }}</h2>
        <!-- 获取home的getters里面的doubleHomeCounter -->
        <h2>{{ $store.getters["home/doubleHomeCounter"] }}</h2>
        <button @click="homeIncrement">home+1</button>
        <button @click="homeIncrementAction">home+1</button>
    </template>
    <script>
      export default {
        methods: {
          homeIncrement() {
            // 指定home模块的commit
            this.$store.commit("home/increment")
          homeIncrementAction() {
            // 指定home模块的dispatch
            this.$store.dispatch("home/incrementAction")
    </script>
    <style scoped>
    </style>
    

    子module的一些参数

    对于模块内部的 mutation 和 getter,接收的第一个参数是模块的局部状态对象,其他参数如下:

    home.js文件代码如下:

    const homeModule = {
      namespaced: true,
      state() {
        return {
          homeCounter: 100
      getters: {
        // 前面我们讲了在根里面的getters里面有state和getters两个参数, 其实在子模块的getters里面还有更多的参数
        // state就是上面的state
        // getters用户获取其他的getters
        // rootState拿到根的state
        // 拿到根getters
        doubleHomeCounter(state, getters, rootState, rootGetters) {
          return state.homeCounter * 2
        otherGetter(state) {
          return 100
      mutations: {
        increment(state) {
          state.homeCounter++
      actions: {
        // 一个参数对齐进行解构
        // commit: 提交
        // dispatch: 分发
        // state: 当前state
        // rootState: 根state
        // getters: 当前getters
        // rootGetters: 根getters
        incrementAction({commit, dispatch, state, rootState, getters, rootGetters}) {
          // 这里提交commit,默认提交的是当前模块的commit
          commit("increment")
          // 如果我们想提交根模块的commit,需要第三个参数
          // 参数一: 提交的方法名字
          // 参数二: payload,也就是传递给increment方法的参数
          // 参数三: {root: true}代表是根的commit
          commit("increment", null, {root: true})
          // 同理dispatch也是一样
          // dispatch("incrementAction", null, {root: true})
          // 上面incrementAction的参数其实是一个context,它和store不一样,它会引用root的一些东西,比如rootState和rootGetters
          // 但是store就没这些参数,这也是他们的区别
    export default homeModule
    

    上面incrementAction的参数其实是一个context,它和store不一样,它会引用root的一些东西,比如rootState和rootGetters,但是store就没这些参数,这也是它们的区别。

    module的辅助函数

    前面我们使用辅助函数是这样使用的:

    computed: {
      ...mapState(["homeCounter"]),
      ...mapGetters(["doubleHomeCounter"])
    methods: {
      ...mapMutations(["increment"]),
      ...mapActions(["incrementAction"]),
    

    这样写只是获取根里面的,如果不是根里面,就需要指定模块名了。

    方式一:通过完整的模块空间名称来查找(用的少);
    方式二:第一个参数传入模块空间名称,后面写上要使用的属性(用的多);
    方式三:通过 createNamespacedHelpers 生成一个模块的辅助函数(用的多);

    关于方式一、方式二的示例如下,一般方式二用的比较多。

    <script>
      import { mapState, mapGetters, mapMutations, mapActions } from "vuex";
      export default {
        computed: {
          // 1.写法一:
          // ...mapState({
            homeCounter: state => state.home.homeCounter
          ...mapGetters({
            doubleHomeCounter: "home/doubleHomeCounter"
          // 2.写法二:
          ...mapState("home", ["homeCounter"]),
          ...mapGetters("home", ["doubleHomeCounter"])
        methods: {
          // 1.写法一:
          ...mapMutations({
            increment: "home/increment"
          ...mapActions({
            incrementAction: "home/incrementAction"
          // 2.写法二
          ...mapMutations("home", ["increment"]),
          ...mapActions("home", ["incrementAction"]),
    </script>
    

    第三种方式:我们可以使用vuex里的createNamespacedHelpers函数,然后解构函数的返回值。

    <script>
      // 导入函数
      import { createNamespacedHelpers } from "vuex";
      // 解构返回值
      const { mapState, mapGetters, mapMutations, mapActions } = createNamespacedHelpers("home")
      export default {
        computed: {
          // 3.写法三:
          ...mapState(["homeCounter"]),
          ...mapGetters(["doubleHomeCounter"])
        methods: {
          // 3.写法三:
          ...mapMutations(["increment"]),
          ...mapActions(["incrementAction"]),
    </script>
    

    通过createNamespacedHelpers函数,我们的写法就和以前在根里面写的一样了,更推荐这种方式。

    在setup中使用

    对于state和getters,如果在setup中使用我们可以用以前封装的useState.js和useGetters.js,但是以前我们封装useState.js和useGetters.js的时候没有考虑模块,所以现在我们要重新封装。

    useState.js文件代码:

    import { mapState, createNamespacedHelpers } from 'vuex'
    import { useMapper } from './useMapper'
    export function useState(moduleName, mapper) {
      let mapperFn = mapState
      // 传模块名和数组
      if (typeof moduleName === 'string' && moduleName.length > 0) {
        mapperFn = createNamespacedHelpers(moduleName).mapState
      } else {
        // 只传数组就是从根里面获取
        mapper = moduleName
      return useMapper(mapper, mapperFn)
    

    useGetters.js文件代码:

    import { mapGetters, createNamespacedHelpers } from 'vuex'
    import { useMapper } from './useMapper'
    export function useGetters(moduleName, mapper) {
      let mapperFn = mapGetters
      if (typeof moduleName === 'string' && moduleName.length > 0) {
        mapperFn = createNamespacedHelpers(moduleName).mapGetters
      } else {
        mapper = moduleName
      return useMapper(mapper, mapperFn)
    

    组件中使用如下:

    setup() {
      // {homeCounter: function}
      const state = useState(["rootCounter"])
      const rootGetters = useGetters(["doubleRootCounter"])
      const getters = useGetters("home", ["doubleHomeCounter"])
      const mutations = mapMutations(["increment"])
      const actions = mapActions(["incrementAction"])
      return {
        ...state,
        ...getters,
        ...rootGetters
        ...mutations,
        ...actions
    

    nexttick

    官方解释:将回调推迟到下一个 DOM 更新周期之后执行。在更改了一些数据以等待 DOM 更新后立即使用它。

    比如我们有下面的需求:点击一个按钮,我们会修改在h2中显示的message,message被修改后,获取h2的高度。

    实现上面的案例我们有三种方式:
    方式一:在点击按钮后立即获取到h2的高度(错误的做法);
    方式二:在updated生命周期函数中获取h2的高度(但是其他数据更新,也会执行该操作);
    方式三:使用nexttick函数;

    <template>
        <h2>{{counter}}</h2>
        <button @click="increment">+1</button>
        <h2 class="title" ref="titleRef">{{message}}</h2>
        <button @click="addMessageContent">添加内容</button>
    </template>
    <script>
      import { ref, onUpdated, nextTick } from "vue";
      export default {
        setup() {
          const message = ref("")
          const titleRef = ref(null)
          const counter = ref(0)
          const addMessageContent = () => {
            message.value += "哈哈哈哈哈哈哈哈哈哈"
            // 先更新DOM
            nextTick(() => {
              // 再打印高度
              console.log(titleRef.value.offsetHeight)
          // nextTick就相当于将我们要执行的操作延迟到DOM更新完之后再执行
          const increment = () => {
            for (let i = 0; i < 100; i++) {
              counter.value++
          // 方式二:在updated生命周期函数中获取h2的高度(但是其他数据更新,也会执行该操作)
          // 比如点击+1的操作,onUpdated也会回调
          onUpdated(() => {
            console.log(titleRef.value.offsetHeight)
          return {
            message,
            counter,
            increment,
            titleRef,
            addMessageContent
    </script>
    <style scoped>
      .title {
        width: 120px;
    </style>
    

    nextTick就相当于将我们要执行的操作延迟到DOM更新完之后再执行。

    那么nexttick是如何做到的呢?事件循环,也就是event loop。

    historyApiFallback

    historyApiFallback是开发中一个非常常见的属性,它主要的作用是解决SPA页面在路由跳转之后,进行页面刷新时,返回404的错误。

  • boolean值,默认是false,如果设置为true,那么在刷新时,返回404错误时,会自动返回 index.html 的内容。
  • object类型的值,可以配置rewrites属性,可以配置from来匹配路径,决定要跳转到哪个页面。
  • 事实上devServer中实现historyApiFallback功能是通过 connect-history-api-fallback 库实现的,可以自己查看文档。Nginx配置的截图如下:

    那么如果我们真想把historyApiFallback改成false,还要去修改源码吗?修改源码固然可以,但是不推荐,我们可以新建vue.config.js文件,这个文件的内容会被读取最后合并到webpack内部,代码如下:

    module.exports = {
      configureWebpack: {
        devServer: {