美文网首页
Vuex 初步学习

Vuex 初步学习

作者: 摸爬打滚 | 来源:发表于2019-07-18 11:49 被阅读0次

    一、概念

    每一个 Vuex 应用的核心就是 store(仓库),它包含着你的应用中大部分的状态 (state)。Vuex 和单纯的全局对象有以下两点不同。

    • Vuex 的状态存储是响应式的。若 store 中的状态发生变化,那么相应的组件也会相应地得到高效更新。
    • 不能直接改变 store 中的状态。改变 store 中的状态的唯一途径就是显式地提交 (commit) mutation。

    简单的设置一个vue的store:

    // 如果在模块化构建系统中,请确保在开头调用了 Vue.use(Vuex)
    
    const store = new Vuex.Store({
      state: {
        count: 0
      },
      mutations: {
        increment (state) {
          state.count++
        }
      }
    })
    
    store.commit('increment')   //使用改变属性的方法
    
    console.log(store.state.count)  // -> 1  直接获取属性的值
    

    二、State

    属性存放位置

    Vuex 使用单一状态树,作为一个“唯一数据源而存在。由于 Vuex 的状态存储是响应式的,从 store 实例中读取状态最简单的方法就是在计算属性中返回某个状态。

    // 创建一个 Counter 组件
    const Counter = {
      template: `<div>{{ count }}</div>`,
      computed: {   //计算属性
        count () {
          return store.state.count
        }
      }
    }
    //每当 store.state.count 变化的时候, 都会重新求取计算属性,并且触发更新相关联的 DOM。
    

    这种模式导致组件依赖全局状态单例,在模块化的构建系统中,在每个需要使用 state 的组件中需要频繁地导入,并且在测试组件时需要模拟状态。

    mapState 辅助函数

    当一个组件需要获取多个状态时候,将这些状态都声明为计算属性会有些重复和冗余。此时可以使用 mapState 辅助函数帮助我们生成计算属性。

    • 写法一:对象形式
    // 在单独构建的版本中辅助函数为 Vuex.mapState
    import { mapState } from 'vuex'
    
    export default {
        computed: mapState({
            count: state => state.count,
            
            countAlias: 'count',   // 传字符串参数 'count' 等同于 `state => state.count`
            
            countPlusLocalState (state) {   // 为了能够使用 `this` 获取局部状态,必须使用常规函数
                return state.count + this.localCount
            }
        })
    }
    
    • 写法二:数组形式(当映射的计算属性的名称与 state 的子节点名称相同时)
    computed: mapState(['count'])   
    
    对象展开运算符

    如何将它与局部计算属性混合使用?需要使用一个工具函数将多个对象合并为一个,以使我们可以将最终对象传给 computed 属性。

    因此有了对象展开运算符,我们可以极大地简化原有的写法:

    import {mapState} from 'vuex'
     
    computed: {
      localComputed () { /* ... */ },   //局部计算属性
      
      // 使用对象展开运算符将此对象混入到外部对象中
      ...mapState({
            count: state => state.countModel.count,  //可以有多个模块文件
      })
      
      //数组形式
      ...mapState(['count'])
    }
    
    组件仍然保有局部状态

    虽然将所有的状态放到 Vuex 会使状态变化更显式和易调试,但也会使代码变得冗长和不直观。如果有些状态严格属于单个组件,最好还是作为组件的局部状态。你应该根据你的应用开发需要进行权衡和确定。

    二、Getter

    获取属性值

    Vuex 允许我们在 store 中定义“getter”(可以认为是 store 的计算属性)。getter 的返回值会根据它的依赖被缓存起来,且只有当它的依赖值发生了改变才会被重新计算
    Getter

    通过属性访问

    • Getter 会暴露为 store.getters 对象,你可以以属性的形式访问这些值:
    store.getters.count
    
    • 接受 state 作为其第一个参数,也可以接受其他 getter 作为第二个参数
    getters: {
      // ...
      doneTodosCount: (state, getters) => {
        return getters.doneTodos.length  //getters是获取的对象
      }
    }
    

    通过方法访问

    • 可以通过让 getter 返回一个函数,来实现给 getter 传参。
    state: {
        todos: [
          { id: 1, text: '...', done: true },
          { id: 2, text: '...', done: false }
        ]
    },
      
    getters: {
      getTodoById: (state) => (id) => {
        return state.todos.find(todo => todo.id === id)
      }
    }
    
    //使用
    store.getters.getTodoById(2) // -> { id: 2, text: '...', done: false }
    

    mapGetters 辅助函数

    将 store 中的 getter 映射到局部计算属性:

    import { mapGetters } from 'vuex'
    
    export default {
      // ...
      computed: {
      // 使用对象展开运算符将 getter 混入 computed 对象中
        ...mapGetters([
          'doneTodosCount',
          'getTodoById',
          doneCount: 'doneTodosCount'  //重新取一个名字
          // ...
        ])
      }
    }
    

    三、Mutation

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

    vuex中mutation都类似于事件:每一个mutation都有一个字符串的类型type和一个回调函数,回调函数即为我们实际修改属性值状态更改的地方,接受 state 作为第一个参数:

    export default{
        mutations: {
            increment (state) {
              state.count++;   // 变更状态
            }
        }
    }
    
    

    不能直接调用一个 mutation的回调函数,该选项更像事件注册,触发increment类型的mutation时,会直接调用改类型下的回调函数,需要相应的type调用store.commit:

    store.commit('increment')
    

    提交载荷(Payload)

    可以向 store.commit 传入额外的参数,即 mutation 的 载荷(payload)

    mutations: {
      increment (state, n) {
        state.count += n
      }
    }
    
    //使用
    store.commit('increment', 10)
    
    

    大多数情况下,载荷应该是一个对象,这样可以包含多个字段并且记录的 mutation 会更易读

    store.commit('increment', {
      amount: 10
    })
    

    对象风格的提交方式

    提交 mutation 可以直接使用包含 type 属性的对象:

    mutations: {
      increment (state, payload) {
        state.count += payload.amount
      }
    }
    
    //对象风格的提交方式
    store.commit({
      type: 'increment',
      amount: 10
    })
    

    Mutation 需遵守 Vue 的响应规则

    因为Vuex 的 store 中的状态是响应式的,因此变更状态时,监视状态的 Vue 组件也会自动更新

    • 最好提前在你的 store 中初始化好所有所需属性。
    • 当需要在对象上添加新属性时,你应该
      • 使用 Vue.set(obj, 'newProp', 123), 或者
      • 以新对象替换老对象
      state.obj = { ...state.obj, newProp: 123 }  //添加一个对象
      
      以上写法
        let { x, y, ...z } = { x: 1, y: 2, a: 3, b: 4 };
        x; // 1
        y; // 2
        z; // { a: 3, b: 4 }
      

    使用常量替代 Mutation 事件类型

    可以使 linter 之类的工具发挥作用,同时把这些常量放在单独的文件中可以对整个 app 包含的 mutation 一目了然,(可以把常量都放在一个单独的文件中,也可以写在当前文件中)

    // mutation-types.js
    export const SOME_MUTATION = 'SOME_MUTATION'
    
    // store.js
    import Vuex from 'vuex'
    import { SOME_MUTATION } from './mutation-types'
    
    const store = new Vuex.Store({
      state: { ... },
      mutations: {
        // 我们可以使用 ES2015 风格的计算属性命名功能来使用一个常量作为函数名
        [SOME_MUTATION] (state) {
          // mutate state
        }
      }
    })
    

    在组件中提交 Mutation

    • 在组件中使用以下代码提交
    this.$store.commit('类型')
    
    • mapMutations 辅助函数
    import { mapMutations } from 'vuex'
    
    export default {
      methods: {
        ...mapMutations([    // `mapMutations` 也支持载荷:
          'increment', 
          'incrementBy'
        ]),
        ...mapMutations({    //重新取名字
          add: 'increment'
        })
      }
    }
    
    //使用
    this.increment();  //映射为 this.$store.commit('increment')
    this.incrementBy(amount);  //映射为this.$store.commit('incrementBy', amount)
    this.add();   //映射为this.$store.commit('increment')
    

    Mutation 必须是同步函数

    ==坚决不能是异步函数== , mutation 都是同步事务

    在 mutation 中混合异步调用会导致你的程序很难调试。当你调用了两个包含异步回调的 mutation 来改变状态,你怎么知道什么时候回调和哪个先回调呢?

    四、Action

    Action 类似于 mutation,区别:

    • Action 提交的是 mutation,而不是直接变更状态。
    • Action 可以包含任意异步操作。
    const store = new Vuex.Store({
      state: {
        count: 0
      },
      mutations: {
        increment (state) {
          state.count++
        }
      },
      actions: {
        increment (context) {
          context.commit('increment')
        }
      }
    })
    

    Action 函数接受一个与 store 实例具有相同方法和属性的 context 对象,可以调用 context.commit 提交一个 mutation,context.state 和 context.getters 来获取 state 和 getters,可以用ES2015 的参数解构increment ({commit,state,getters})

    分发 Action

    Action 通过 store.dispatch 方法触发:

    store.dispatch('increment')
    

    可以在 action 内部执行异步操作,支持同样的载荷方式和对象方式进行分发:

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

    在组件中分发 Action

    • 直接使用dispatch分发
      this.$store.dispatch('xxx')
      
    • 使用mapActions 辅助函数
      import { mapActions } from 'vuex'
      export default {
          methods: {
            ...mapActions(['increment', 'incrementBy' ]),
            ...mapActions({
              add: 'increment' 
            })
          }
          mounted() {
              this.increment();   // 映射为this.$store.dispatch('increment')
              this.incrementBy(amount);   //映射为this.$store.dispatch('incrementBy', amount)
              this.add();   //映射为this.$store.dispatch('increment')
          }
      }
      

      组合 Action

      store.dispatch 可以处理被触发的 action 的处理函数返回的 Promise,并且 store.dispatch 仍旧返回 Promise
      actions: {
          actionA ({ commit }) {
            return new Promise((resolve, reject) => {
              setTimeout(() => {
                commit('someMutation')
                resolve()
              }, 1000)
            })
          },
          actionB ({ dispatch, commit }) {
            return dispatch('actionA').then(() => {
              commit('someOtherMutation')
            })
          }
      }
      
    • 可以利用 async / await
      // 假设 getData() 和 getOtherData() 返回的是 Promise
      
        actions: {
          async actionA ({ commit }) {
            commit('gotData', await getData())
          },
          async actionB ({ dispatch, commit }) {
            await dispatch('actionA') // 等待 actionA 完成
            commit('gotOtherData', await getOtherData())
          }
        }
      

    Module

    当应用变得非常复杂时,store就会有很多,此时Vuex 允许我们将 store 分割成模块。每个模块拥有自己的 state、mutation、action、getter、甚至是嵌套子模块——从上至下进行同样方式的分割:

    // moduleA.js
    export default moduleA = {
      state: { ... },
      mutations: { ... },
      actions: { ... },
      getters: { ... }
    }
    
    //store.js
    import Vue from 'vue'
    import Vuex from 'vuex'
    import moduleA from './moduleA'
    
    Vue.use(Vuex)
    
    const moduleB = {
      state: { ... },
      mutations: { ... },
      actions: { ... }
    }
    
    export default  new Vuex.Store({
      modules: {
        moduleA,
        b: moduleB
      }
    })
    
    
    • 对于模块内部的 mutation 和 getter,接收的第一个参数是模块的局部状态对象。
    • 对于模块内部的 action,局部状态通过 context.state 暴露出来;根节点状态则为 context.rootState
    • 对于模块内部的 getter,根节点状态rootState会作为第三个参数暴露出

    命名空间

    [复杂]

    带命名空间的绑定函数
    computed: {
      ...mapState('some/nested/module', {
        a: state => state.a,
        b: state => state.b
      })
    },
    
    • 你可以通过使用 createNamespacedHelpers 创建基于某个命名空间辅助函数,返回一个对象,对象里有新的绑定在给定命名空间值上的组件绑定辅助函数:

        import { createNamespacedHelpers } from 'vuex'
        const { mapState, mapActions } = createNamespacedHelpers('some/nested/module')
        export default {
          computed: {
            ...mapState({
              a: state => state.a,
              b: state => state.b
            })
          }
        }
      

    后面会更新具体在项目中的使用

    相关文章

      网友评论

          本文标题:Vuex 初步学习

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