zoukankan      html  css  js  c++  java
  • vuex详解

    vuex详解

      yarn add vuex

    1、vuex流程图

      vuex可以帮助我们管理组件间公共的数据

      创建一个 store 

    // 如果在模块化构建系统中,请确保在开头调用了 Vue.use(Vuex)
    
    const store = new Vuex.Store({
      state: {
        count: 0
      },
      mutations: {
        increment (state) {
          state.count++
        }
      }
    })

      现在,你可以通过 store.state 来获取状态对象,以及通过 store.commit 方法触发状态变更:

    store.commit('increment')
    
    console.log(store.state.count) // -> 1

    2、详解(state)

      

      由于 Vuex 的状态存储是响应式的,从 store 实例中读取状态最简单的方法就是在计算属性中返回某个状态:

    // 创建一个 Counter 组件
    const Counter = {
      template: `<div>{{ count }}</div>`,
      computed: {
        count () {
          return store.state.count
        }
      }
    }

      

      每当 store.state.count 变化的时候, 都会重新求取计算属性,并且触发更新相关联的 DOM。

      这种模式导致组件依赖全局状态单例

      所以,

      Vuex 通过 store 选项,提供了一种机制将状态从根组件“注入”到每一个子组件中(需调用 Vue.use(Vuex)):

    const app = new Vue({
      el: '#app',
      // 把 store 对象提供给 “store” 选项,这可以把 store 的实例注入所有的子组件
      store,
      components: { Counter },
      template: `
        <div class="app">
          <counter></counter>
        </div>
      `
    })

      

      通过在根实例中注册 store 选项,该 store 实例会注入到根组件下的所有子组件中,且子组件能通过 this.$store 访问到。让我们更新下 Counter 的实现:

    const Counter = {
      template: `<div>{{ count }}</div>`,
      computed: {
        count () {
          return this.$store.state.count
        }
      }
    }

      mapState辅助函数

      当一个组件需要获取多个状态时候,将这些状态都声明为计算属性会有些重复和冗余。

      为了解决这个问题,我们可以使用 mapState 辅助函数帮助我们生成计算属性,让你少按几次键:

    // 在单独构建的版本中辅助函数为 Vuex.mapState
    import { mapState } from 'vuex'
    
    export default {
      // ...
      computed: mapState({
        // 箭头函数可使代码更简练
        count: state => state.count,
    
        // 传字符串参数 'count' 等同于 `state => state.count`
        countAlias: 'count',
    
        // 为了能够使用 `this` 获取局部状态,必须使用常规函数
        countPlusLocalState (state) {
          return state.count + this.localCount
        }
      })
    }

    3、详解(Getter)

      个人理解:相当于获取计算后的state,将state中某个状态进行过滤,然后获取新的状态

      Vuex 允许我们在 store 中定义“getter”(可以认为是 store 的计算属性)。

      就像计算属性一样,getter 的返回值会根据它的依赖被缓存起来,

      且只有当它的依赖值发生了改变才会被重新计算。

      Getter 接受 state 作为其第一个参数:

    const store = new Vuex.Store({
      state: {
        todos: [
          { id: 1, text: '...', done: true },
          { id: 2, text: '...', done: false }
        ]
      },
      getters: {
        doneTodos: state => {
          return state.todos.filter(todo => todo.done)
        }
      }
    })

      Getter 会暴露为 store.getters 对象,你可以以属性的形式访问这些值:

    store.getters.doneTodos // -> [{ id: 1, text: '...', done: true }]

      Getter 也可以接受其他 getter 作为第二个参数:

    getters: {
      // ...
      doneTodosCount: (state, getters) => {
        return getters.doneTodos.length
      }
    }

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

    getters: {
      // ...
      getTodoById: (state) => (id) => {
        return state.todos.find(todo => todo.id === id)
      }
    }
    
    
    
    store.getters.getTodoById(2) // -> { id: 2, text: '...', done: false }

      getter 在通过方法访问时,每次都会去进行调用,而不会缓存结果

      mapGetters辅助函数

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

    import { mapGetters } from 'vuex'
    
    export default {
      // ...
      computed: {
      // 使用对象展开运算符将 getter 混入 computed 对象中
        ...mapGetters([
          'doneTodosCount',
          'anotherGetter',
          // ...
        ])
      }
    }

    4、详解(Mutation)

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

      Vuex 中的 mutation 非常类似于事件:

      每个 mutation 都有一个字符串的 事件类型 (type) 和 一个 回调函数 (handler)。

      这个回调函数就是我们实际进行状态更改的地方,

      并且它会接受 state 作为第一个参数:

    const store = new Vuex.Store({
      state: {
        count: 1
      },
      mutations: {
        increment (state) {
          // 变更状态
          state.count++
        }
      }
    })





    store.commit('increment')
     

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

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

      mutation 必须是同步函数

      
      你可以在组件中使用 this.$store.commit('xxx') 提交 mutation,

      或者使用 mapMutations 辅助函数将组件中的 methods 映射为 

      store.commit 调用(需要在根节点注入 store)。

    import { mapMutations } from 'vuex'
    
    export default {
      // ...
      methods: {
        ...mapMutations([
          'increment', // 将 `this.increment()` 映射为 `this.$store.commit('increment')`
    
          // `mapMutations` 也支持载荷:
          'incrementBy' // 将 `this.incrementBy(amount)` 映射为 `this.$store.commit('incrementBy', amount)`
        ]),
        ...mapMutations({
          add: 'increment' // 将 `this.add()` 映射为 `this.$store.commit('increment')`
        })
      }
    }

    5、详解(Action)

      Action 类似于 mutation,不同在于:

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

      我们可以在 action 内部执行异步操作:

    actions: {
      incrementAsync ({ commit }) {
        setTimeout(() => {
          commit('increment')
        }, 1000)
      }
    }

      Actions 支持同样的载荷方式和对象方式进行分发: 

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

      在组件中使用 this.$store.dispatch('xxx') 分发 action,

      或者使用 mapActions 辅助函数将组件的 methods 映射为 

      store.dispatch 调用(需要先在根节点注入 store):

    import { mapActions } from 'vuex'
    
    export default {
      // ...
      methods: {
        ...mapActions([
          'increment', // 将 `this.increment()` 映射为 `this.$store.dispatch('increment')`
    
          // `mapActions` 也支持载荷:
          'incrementBy' // 将 `this.incrementBy(amount)` 映射为 `this.$store.dispatch('incrementBy', amount)`
        ]),
        ...mapActions({
          add: 'increment' // 将 `this.add()` 映射为 `this.$store.dispatch('increment')`
        })
      }
    }

      store.dispatch 可以处理被触发的 action 的处理函数返回的 Promise,

      并且 store.dispatch 仍旧返回 Promise:

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

      

      一个action中

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

      另一个action中

    actions: {
      // ...
      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())
      }
    }

      一个 store.dispatch 在不同模块中可以触发多个 action 函数。

      在这种情况下,只有当所有触发函数完成后,返回的 Promise 才会执行。

     
     

    以后再更。

  • 相关阅读:
    Java入门——(3)面对对象(下)
    Java入门——(8)网络编程
    Java入门——(2)面对对象(上)
    MAC下的Intellij IDEA常用快捷键
    RedHat安装yum+配置国内yum源
    XGBoost算法
    Bagging和Boosting 概念及区别
    关于python的sort和sorted
    sklearn中常用数据预处理方法
    安装Scala
  • 原文地址:https://www.cnblogs.com/yangyangxxb/p/10096540.html
Copyright © 2011-2022 走看看