之前也講過了,actions中是用來操作異步代碼的,由於在mutations寫異步操作會導致devtools工具記錄不到state的變化,因此才有actions的存在,下面是基本的使用,如下:
點擊按鈕,發布到actions:
<template> <div> <button @click="toAjax">發起異步請求</button> </div> </template> methods: { toAjax(){ this.$store.dispatch('sendAjax') } }
定義sendAjax,並提交到mutations:
mutations: { msendAjax(state){ state.counter++ } } actions: { sendAjax(context){ //異步操作 setTimeout(()=>{ context.commit('msendAjax') },1000) } }
上面的context對象相當於state,擁有一些和state相同的方法。上面只是基本的使用,如果在dispatch要傳遞參數,和commit傳遞參數要怎么做呢?如下:
methods: { toAjax(){ const arg = '我是參數' this.$store.dispatch('sendAjax',arg) } }
mutations: { msendAjax(state,payload){ console.log(payload) state.counter++ } }, actions: { sendAjax(context,arg){ setTimeout(()=>{ context.commit('msendAjax',arg) },1000) } }
上面是actions無參和有參的基本使用了。但實際開發中,在actions中方法執行完畢了,要給componnet返回結果告訴操作已經完成,那該如何做呢? 如下:
<template> <div> <button @click="toAjax">發起異步請求</button> </div> </template>
methods: { toAjax(){ const arg = '我是參數' this.$store .dispatch('sendAjax',arg) .then(() => { console.log('dispatch已經完成了') }) } }
mutations: { msendAjax(state,payload){ console.log(payload) state.counter++ } }, actions: { sendAjax(context,arg){ return new Promise(resolve => { setTimeout(()=>{ context.commit('msendAjax',arg) resolve() },1000) }) } }
參數該怎么傳還怎么傳,原本的異步代碼用 new Promise包裹起來,然后.then不要在actions中寫,在components寫會比較明顯易懂