Vuex 使用笔记

 

Vuex 使用笔记

在使用Vuex之前需要使用Vue声明组件 

  1. Vue.use(Vuex)
  2. let store = new Vuex.store({
  3.     state,// Vuex中保存数据 
  4.     mutations, // 对Vuex中的state中的数据进行操作 
  5.     actions, //使用 commit() 对mutations操作
  6.     getters //类似于computed计算属性 
  7. })
  8. new Vue({ store })

需要使用在Vue中绑定 store
Store声明之后回创建一个 $store对象  $store对象中有 Vuex中的state对象 以及 getter对象 可通过$store.state 或者$store.getter 的方法调用
actions对象 需要通过dispatch方法调用 如 
methods:{
        add(){ dispatch("addcount","可以传输的数据") }
}
vuex中的actions 对象
let actions = {   
    addcount({commit,state},val){  
        commit( "addcounts",val )  
    }  
}
Vuex中的mutations 对象
let mutations = {
    addcounts(state,val){ // 
        state.count += val
    }
}
Vuex中的state 对象 
let state = {
    count:0,
}

Vuex中的getters对象 使用方法 
let getters = {
    decrement(state){
        state.count
    }

调用在对应vue组件中
  computed:{
       dec(){
           return this.$store.getters.decrement; //在getters中定义的函数不需要调用 因为为getter方法 在数据读取时会自动调用
       }
  }