美文网首页Vue.js
vuex--状态管理用法解析

vuex--状态管理用法解析

作者: 花拾superzay | 来源:发表于2020-01-11 15:48 被阅读0次

基本使用

//store.js文件
Import  Vue  from  ‘vue’
Import  Vuex  from  “vuex”

Vue.use(Vuex)

let  store  =  new  Vuex.Store({
  state:{
     count:0
  },
  getters:{
      count( state) {
          return state.count
      }
  },
  mutations:{
      increment (state) {
          // 变更状态
          state.count++
      }
  },
  actions:{
       incrementAsync ({ commit }) {
           setTimeout(() => {
               commit('increment')
           }, 1000)
       }
   }
})


export  default  store

state属性引用

state下的状态,可以在每个vue实例下通过this.$store.state.count引用

getter属性

其类似于计算属性computed。对getter引用方法是this.$store.getters.count

mapGetters 使用方法

import { mapGetters } from 'vuex'
export default {
   computed: {
     ...mapGetters([
      'count',
    ])
  }
}

mutations

可以在每个vue实例下,使用 this.$sotre.commit('increment',参数) 方法触发mutations的方法

mapMutations使用方法

import { mapMutations } from 'vuex'
export default {
  methods: {
    ...mapMutations([
     'increment '// `this.increment ()` 映射为 `this.$store.commit('increment ', amount)`
    ]),
    ...mapMutations({
      add: 'increment' // 重命名,将 `this.add()` 映射为 `this.$store.commit('increment')`
    })
  }
}

actions

可以在每个vue实例下,使用 this.$sotre.dispatch('incrementAsync ',参数) 方法触发actions的方法

mapActions

import { mapActions } from 'vuex'
export default {
  methods: {
    ...mapActions([
      'incrementAsync '//将 `this.incrementAsync ()` 映射为 `this.$store.dispatch('incrementAsync ')`
    ]),
    ...mapActions({
      addAsync: 'incrementAsync ' // 重命名,将 `this.addAysnc()` 映射为 `this.$store.dispatch('incrementAsync ')`
    })
  }
}

module模式用法demo

const moduleA = {
  namespaced:true,
  state: { 
     count:0
  },
getters: { 
      doubleCount (state,getters,rootState) {
        return state.count * 2
      }
   },
  mutations: { 
      increment (state,arg) {
         // 这里的 `state` 对象是模块的局部状态
         state.count++
      }
  },
  actions: { 
     incrementIfOddOnRootSum ({ state, commit, rootState },arg) {
         if ((state.count + rootState.count) % 2 === 1) {
           commit('increment')
         }
      }
  },
}


const store = new Vuex.Store({
  modules: {
    a: moduleA,

  }
})

store.state.a // -> moduleA 的状态

state的引用,this.$store.state.a.count
getters的引用,this.$store.getters[‘a/doubleCount ’]
mutations触发,this.$store.commit(‘a/increment ’,参数)
actions触发,this.$store.dispatch(‘a/incrementIfOddOnRootSum ’,参数)

相关文章

网友评论

    本文标题:vuex--状态管理用法解析

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