15-Vuex基础

作者: 差一点没吃西瓜 | 来源:发表于2019-12-18 11:01 被阅读0次

    Vue之vuex状态管理

    Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式

    这个Vuex包含以下几个属性部分:

    • Action:和mutation的功能大致相同

    • State:vuex的基本数据,用来存储变量

    • Mutation:提交更新数据的方法,必须是同步的(如果需要异步使用action)。每个 mutation 都有一个字符串 的 事件类型 (type) 和 一个 回调函数 (handler)。

    • Module:模块化vuex,可以让每一个模块拥有自己的state、mutation、action、getters,使得结构非常清晰,方便管理

    • Getter:从基本数据(state)派生的数据,相当于state的计算属性

    那么好的我们Actions开始讲起

    1.Action

    Action 类似于 mutation,不同在于:

    • Action 提交的是 mutation,而不是直接变更状态。
    • Action 可以包含任意异步操作

    我们先来注册一个action

      state: {
        count: 0
      },
      mutations: {
        add (state) {
          state.count++
        },
        decrease (state) {
          state.count--
        }
      },
      actions: {
        delayAdd (context) {
          setTimeout(() => {
              //通过context提交一个mutation
            context.commit('add')
          }, 1000)
        }
      },
    

    Action 函数接受一个与 store 实例具有相同方法和属性的 context 对象,因此你可以调用 context.commit 提交一个 mutation,或者通过 context.statecontext.getters 来获取 state 和 getters。

    Action 通过 store.dispatch 方法或者用辅助函数mapActions触发:

    // 以载荷形式分发
    store.dispatch('add', {
      amount: 10
    })
    
    // 以对象形式分发
    store.dispatch({
      type: 'add',
      amount: 10
    })
    

    很多时候我们一般使用commit比较多,但是又不想引入context,我们更多时候采用参数结构的方式

    actions: {
      delayAdd ({ commit }) {
        commit('add')
      }
    }
    

    我们一直说Action 通常是异步的,那么如何知道 action 什么时候结束呢?更重要的是,我们如何才能组合多个 action,以处理更加复杂的异步流程?

    store.dispatch 可以处理被触发的 action 的处理函数返回的 Promise,并且 store.dispatch 仍旧返回 Promise:

    举个栗子

    actions: {
      actionA ({ commit }) {
        return new Promise((resolve, reject) => {
          setTimeout(() => {
            commit('someMutation')
            resolve()
          }, 1000)
        })
      }
    }
    

    我们去使用触发的时候

    store.dispatch('actionA').then(() => {
      // ...
    })
    

    或者别的地方我们还想用

    actions: {
      // ...
      actionB ({ dispatch, commit }) {
        // 等待A
        return dispatch('actionA').then(() => {
          commit('someOtherMutation')
        })
      }
    }
    

    当然了有了asyncawait以后更方便

    // 假设 getData() 和 getOtherData() 返回的是 Promise
    
    actions: {
      async actionA ({ commit }) {
        // 提交getData(),等待返回结果
        commit('gotData', await getData())
      },
      async actionB ({ dispatch, commit }) {
        await dispatch('actionA') // 等待 actionA 完成
        commit('gotOtherData', await getOtherData())
      }
    }
    

    2.State

    单一状态值

    我们在Vue组件中要读取Vuex中的状态值一般有两种方式

    第一种方式: this.$store.state

    注释:这里读取的就是上面state进行存放的值

    <template>
      <div class="home">
        <h3>This is an home page</h3>
        <div style="color: red">{{count}}</div>
      </div>
    </template>
    
    <script>
    // @ is an alias to /src
    
    export default {
      name: 'home',
      // 一般在计算属性里面去监听处理数据值
      computed: {
        count () {
          // 通过this.$store.state去读取存放的变量值
          return this.$store.state.count
        }
      },
    }
    </script>
    
    

    第二种方式: mapState辅助函数

    官方文档中给的mapState函数里,给了三种获取方式

    computed: mapState({
        // 第一种我们使用箭头函数
        count: state => state.count,
        
        // 第二种传字符串'count'等同于上面'state => state.count'(建议使用)
        countAlias: 'count'
        
        // 为了能够使用 `this` 获取局部状态,必须使用常规函数
        countPlusLocalState (state) {
          return state.count + this.localCount
        }
    })
    

    我们这里写了代码采用了第二种方式,也是我个人经常用的一种

    <template>
      <div class="home">
        <h3>This is an home page</h3>
        <div style="color: red">{{count}}</div>
      </div>
    </template>
    
    <script>
    // 第一步先引入mapState函数
    import { mapState } from 'vuex'
    export default {
      name: 'home',
      // 第二步去使用这个函数  
      computed: mapState({
        // 通过传字符串的方式取值
        count: 'count'
      })
    }
    </script>
    
    

    当然了,我们要知道es6的语言魅力很多,当映射的计算属性的名称与 state 的子节点名称相同时,我们也可以给 mapState 传一个字符串数组。

    !!!切记这是一个数组哦,不要写成了大括号{}

    computed: mapState([
        // 映射 this.count 为 store.state.count
        'count'
    ])
    

    可能接下来有同学就会问,如果我既要使用计算属性,又要用mapState呢

    那么接下来我们可能会用到这个对象展开符: 嘻嘻,传说中的点点点...

    举个栗子

    computed: {
      localComputed () { /* ... */ },
      // 使用对象展开运算符将此对象混入到外部对象中
      ...mapState([
        'count'
      ])
    }
    

    3.Mutation

    我们介绍这个之前我们首先要明白的是:更改 Vuex 的 store 中的状态的唯一方法是提交 mutation

    mutation 必须是同步函数

    前面讲Actions的时候我们已经在mutations里面封装了加减函数,接下来我就要说组件里面怎么去提交mutation,去更改Vuex的store中的状态

    第一种方式:组件上绑定一个方法,然后在方法里面去提交mutation

    <template>
      <div class="home">
        <h3>This is an home page</h3>
        <div style="color: red">{{count}}</div>
        <button @click="add">增加count</button>
      </div>
    </template>
    
    <script>
    import { mapState } from 'vuex'
    export default {
      name: 'home',
      computed: {
        ...mapState({
          count: 'count'
        })
      },
      methods: {
        add () {
          // 点击触发提交给Mutation,触发add方法
          this.$store.commit('add')
        }
      }
    }
    </script>
    
    

    第二种方式:还是继续使用辅助函数,嘿嘿用起来以后真香,这次这个函数叫mapMutations

     methods: {
       ...mapMutations([
         'increment', // 将 `this.increment()` 映射为 `this.$store.commit('increment')`
    
         // `mapMutations` 也支持载荷(传多个参数):
         // 将 `this.incrementBy(amount)` 映射为 `this.$store.commit('incrementBy', amount)`
         'incrementBy' 
       ]),
      ...mapMutations({
          add: 'increment' // 将 `this.add()` 映射为 `this.$store.commit('increment')`
      })
    }
    

    一些其他的知识点:

    提交载荷(Payload)

    定义:store.commit 传入额外的参数,即 mutation 的 载荷(payload)

    1.比如我们在mutations中定义

    mutations: {
      // 此处我们传入多个参数
      increment (state, n) {
        state.count += n
      }
    }
    

    提交的时候就是这样了

    store.commit('increment', 10)
    

    2.但更多时候我们载荷是一个对象

    举个栗子

    mutations: {
      // 这里payload是一个对象
      increment (state, payload) {
        state.count += payload.amount
      }
    }
    
    // 第一种方式
    store.commit('increment', {
      amount: 10
    })
    // 第二种方式
    store.commit({
      type: 'increment',
      amount: 10
    })
    

    使用常量替代 Mutation 事件类型

    为什么会来介绍这个呢,我们想想一般比较大型的项目,人员多,mutation里面的方法众多,我们定义一个常量方法,在store.js中引用,去mutation中使用,统一的去管理,是不是给人更清晰直观的感受更容易知道

    // 我们随便选择新建一个管理的js,比如叫mutation-types.js,我们在这里去新建mutation的方法,统一管理
    export const ADD_MUTATION = 'ADD_MUTATION'
    export const Delete_MUTATION = 'Delete_MUTATION'
    
    //我们在store.js里面要去引用这个常量
    import {ADD_MUTATION, Delete_MUTATION} from './mutation-types.js'
    
    mutations: {
        // 我们可以使用 ES6 风格的计算属性命名功能来使用一个常量作为函数名
        [ADD_MUTATION] (state) {
            // 进行增加操作啊
        }
        [Delete_MUTATION] (state) {
            // 进行删除操作
        }
    }
    

    4.Module

    使用单一状态树,应用的所有状态会集中到一个比较大的对象。当应用变得非常复杂时,store 对象就有可能变得相当臃肿。

    为了解决以上问题,Vuex 允许我们将 store 分割成模块(module)。每个模块拥有自己的 state、mutation、action、getter、甚至是嵌套子模块——从上至下进行同样方式的分割:

    const moduleA = {
      state: { ... },
      mutations: { ... },
      actions: { ... },
      getters: { ... }
    }
    
    const moduleB = {
      state: { ... },
      mutations: { ... },
      actions: { ... }
    }
    // 放进store中
    const store = new Vuex.Store({
      modules: {
        a: moduleA,
        b: moduleB
      }
    })
    
    store.state.a // -> moduleA 的状态
    store.state.b // -> moduleB 的状态
    

    我们可以到这便是简单基础的模块划分,更多的时候,我们一般才用的是多个文件,比如a.js里面我就写moduleA,b.js里面我就写moduleB,然后给导出,最后统一在index.js引入,在总模块中使用

    5.Getter

    从基本数据(state)派生的数据,相当于state的计算属性

    便于多个组件使用,也是在组件的computed属性中读取this.$store.getters

    1.通过对象来访问

      state: {
        todos: [
          { id: 1, text: '...', done: true },
          { id: 2, text: '...', done: false }
        ]
      },
      getters: {
        // Getter接受state作为其第一个参数
        doneTodos: state => {
          return state.todos.filter(todo => todo.done)
        }
        /** Getter 也可以接受其他 getter 作为第二个参数: **/
        doneTodosCount: (state, getters) => {
          // 这里我们去读取第一个doneTodos里面的参数
          return getters.doneTodos.length
        }
      }
    
      computed: {
        doneTodos () {
          // 通过this.$store.getters来获取
          return this.$store.getters.doneTodos
        }
      },
    

    2.通过方法来访问

    通过让 getter 返回一个函数,来实现给 getter 传参。在你对 store 里的数组进行查询时非常有用。

      state: {
        todos: [
          { id: 1, text: '...', done: true },
          { id: 2, text: '...', done: false }
        ]
      },
      getters: {
        // 目的就是方便我去查询state里面存放的值
        getTodosId: (state) => (id) => {
          return state.todos.find(todo => todo.id === id)
        }
      },
    

    3.辅助函数mapGetters

      // 在组件中引入辅助函数mapGetters
      import {mapgetters} from 'vuex'
    
      // 在组件的computed里面
      computed: {
        //同名的话
        ...mapGetters([
            'doneTodos'
        ])
        //或者你想换个名字
        ...mapGetters({
          doneTodos: 'doneTodos'
        })    
      },
    

    换名字采用的是对象的形式:所以要记得用{}

    相关文章

      网友评论

        本文标题:15-Vuex基础

        本文链接:https://www.haomeiwen.com/subject/ewwynctx.html