vuex详解

vuex详解

  yarn add vuexhtml

一、vuex流程图vue

  vuex能够帮助咱们管理组件间公共的数据git

  建立一个 store github

// 若是在模块化构建系统中,请确保在开头调用了 Vue.use(Vuex)

const store = new Vuex.Store({
  state: {
    count: 0
  },
  mutations: {
    increment (state) {
      state.count++
    }
  }
})

 

  如今,你能够经过 store.state 来获取状态对象,以及经过 store.commit 方法触发状态变动:vuex

store.commit('increment')

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

 

 


 

 

二、详解(state)数组

  

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

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

  

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

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

  因此,异步

  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
    }
  })
}

 


 

 

三、详解(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',
      // ...
    ])
  }
}

 


 

 

四、详解(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')`
    })
  }
}

 


 

 

五、详解(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 才会执行。

 

 
 

 

 

之后再更。

相关文章
相关标签/搜索