vuex簡單梳理4,actions的用法和其輔助函式
阿新 • • 發佈:2020-09-08
actions用來呼叫非同步的方法,再通過觸發Mutations來修改state
現在雖然在Mutations中呼叫非同步方法也不會報錯了,但是也要遵守vuex中的規則,也為日後維護的人員增加程式碼的可讀性。
const state = { s:0, }
const mutations = { SET_S(state,num){ state.s = num; } }
const actions = { sum({commit},params){//預設的引數commit,通過commit來呼叫定義在Mutations中的方法 setTimeout(()=>{ console.log(params.a-0,params.a) commit("SET_S",(params.a - 0 )+ (params.b - 0)) },3000) }, }
元件中同dispatch呼叫actions中的方法
<div> <h3>actions</h3> <input type="text" ref="a">+ <input type="text" ref="b"> <input type="button" @click="$store.dispatch('sum',{a:$refs.a.value,b:$refs.b.value})" value="=">//通過dispatch呼叫<input type="button" @click="sum({a:$refs.a.value,b:$refs.b.value})" value="=">//輔助函式 {{$store.state.s}} </div>
其輔助函式用法與之前型別
import{mapActions}from"vuex";methods:{...mapActions(["sum",'test']), ...{ set(num){this.$store.dispatch('test',num) console.log(this.$store,'vuex狀態') } } }
這裡多說一句,當我在實際專案中通過封裝好的axios或者直接使用promise,在非同步中再呼叫非同步時就會 體會到actions的好處
vuex的梳理告一段落