2019年3月6日 星期三

【Vuex】Store的寫法:mutation、action、payload


▌Store寫法

  • state:資料的狀態
  • mutations:改變state的值,
    increment(state){
    this.state.count++ 
    }
    
  • actions:去commit mutation
    increment:({commit})=>commit("increment")
    

▌vue寫法

  • this.$store.dispatch(“action的名稱”)
    increment(){
    this.$store.dispatch("increment")
    }
    
  • this.$store.commit(“mutation的名稱”)
    increment(){
    this.$store.commit("increment")
    }
    

▌範例

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const state={
  num:0
}

const mutations={
  increment(state){
    state.num ++
  },
  descrement(state){
    state.num --
  }
}

const actions ={
  increment:({commit})=> commit("increment"),
  descrement:({commit})=> commit("descrement")
}

export default new Vuex.Store({
  state,
  mutations,
  actions
})

載荷寫法 Payload

▌vue

-vue:descrement ( ){ this.$store.dispatch(“descrement”,this.pay) }
  descrement(){
    this.$store.dispatch("descrement",this.pay)
  }
  increment(){
    this.$store.dispatch("increment",this.pay)
  }

▌store

  • action: increment:({commit},payload)=> commit(“increment”,payload),
  • mutation:increment(state,payload){ state.num +=payload}
const state={
  num:0
}

const mutations={
  increment(state,payload){
    state.num +=payload
  },
  descrement(state,payload){
    state.num -=payload
  }
}

const actions ={
  increment:({commit},payload)=> commit("increment",payload),
  descrement:({commit},payload)=> commit("descrement",payload)
}

沒有留言:

張貼留言