vuex概念理解

01、State

this.$store.state.count
在计算属性中获取
const Counter = {
  template: `
{{ count }}
`
, computed: { count () { return this.$store.state.count } } }
mapState 辅助函数

用法一:

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

用法二:

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

2、Getter

this.$store.getters.someAttr
通过属性访问
getters: {
  // ...
  Count: (state, [getters]) => {
    return getters.anothergetters.age
  }
}

//调用取值
store.getters.Count
通过方法访问
getters: {
  // ...
  getTodoById: (state) => (id) => {
    return state.todos.find(todo => todo.id === id)
  }
}

//调用取值
store.getters.getTodoById(2) // -> { id: 2, text: '...', done: false }
mapGetters 辅助函数
mapGetters({
  // 把 `this.doneCount` 映射为 `this.$store.getters.doneTodosCount`
  doneCount: 'doneTodosCount'
})

3、mutation

定义
mutations: {
  increment (state, payload) {
    state.count += payload.amount
  }
}

this.$store.commit('increment', {
  amount: 10
})
直接提交
this.$store.commit('increment', {
  amount: 10
})
mapMutations 辅助函数
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')`
    })
  }
}

4.1、action

定义
actions: {
  increment ({ commit }) {
    commit('increment')
  }
}
分发
store.dispatch('increment')
mapActions 辅助函数
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)`
    ])
  }
}

4.2、异步actions

  • 定义
actions: {
  actionA ({ commit }) {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        commit('someMutation')
        resolve()
      }, 1000)
    })
  }
}
  • 使用
store.dispatch('actionA').then(() => {
  // ...
})

5、Module

参考链接

你可能感兴趣的:(vue,vuex)