Vuex的使用方法简要

写在前面:如果有对Vuex还不知道怎么用或者觉得看官方文档吃力的童鞋,建议读一下这一篇https://segmentfault.com/a/1190000009404727

1. 使用state

state:{
  todos:[
    { id: 1, text: '...', done: true },
    { id: 2, text: '...', done: false}
}

  

2. 使用getters

getters的作用相当于组建中的computed,可以对state中的数据进行过滤并展示:

 getters:{
  doneTodos: state => {
      return state.todos.filter(todo => todo.done)
    }
}

3. 使用mutation

mutations:{
    increment (state) { //mutation事件类型接受state作为参数
        state.count++
    }
}    

调用方式如下:

store.commit('increment')

提交载荷(Payload)意思是像state.commit传入额外的参数,大多数情况,载荷应该是一个对象,这样更易读

mutations:{
    increment (state, payload){
        state.count += payload.amount
    }
}
store.commit('increment', {
    amount:10
})
//也可以使用对象风格提交mutation:
store.commit({ type: 'increment', amount: 10 })

注意:mutation只能是同步函数

4. 使用actions
actions使用方法与mutations一样,区别在于action只能是异步函数,而mutations里面只能是同步函数

actions:{
    increment (context) {
        context.commit('increment')
    }
}
//context是一个与context有相同方法和属性的对象    

5. 在组件中使用Vuex

在组件中的调用方法为

state: $store.state.dialog.show
getters: $store.getters.functionname
mutations: $store.commit('switch_dialog')
actions: $store.dispatch('switch_dialog')

不过这种写法又臭又长,更好的做法是使用mapState、mapGetters和mapActions

state:
import { mapState } from 'Vuex'
computed:mapState({
    localComputed(){}
    //使用对象展开运算符将此对象混入到外埠对象中
    ...mapState({
        show:false
        //......
    })
})
getters:
import { mapGetters } from 'Vuex'
computed:{
    ...mapGetters({
    'doneTodoCount'
         //或者可以给getter属性另取一个名字
         doneCount:'doneTodoCount'
    })
}
mutations:
import { mapMutations } from 'Vuex'
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')`
  })
}
actions:
import { mapActions } from 'Vuex'
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')`
  })
}

  

原文地址:https://www.cnblogs.com/wangwg1994/p/9206174.html