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)
}

沒有留言:

張貼留言

【JavaScript】用物件Mapping的方法

If的寫法 我們希望當變數是a時就回傳1,變數是b就回傳2,變數是c就會回傳3,一般寫法就是用if,但是這樣會很冗 ​ // IF style var word if(word == 'a'){ word = 1 } else if...