一、定义 actions 方法
export default new Vuex.Store({actions: {async getStudentsAsync(context) {const res = await api.students.get();console.log('后端返回的结果:', res);}}})
二、调用 actions 方法
组件中调用 actions 的方法:
export default {created() {// 调用组件自己的 methodsthis.getStudents();},methods: {getStudents() {// 组件中调用 actionsthis.$store.dispatch('getStudentsAsync');}}}
三、将 actions 结果交给组件
要将 actions 的请求结果交给组件,有两种方式:
- 把请求结果保存到 state,组件从 state 中获取请求结果;
- 把请求结果通过 return 返回,组件中直接接收 actions 方法的返回值;
1、将 actions 结果保存到 state
因为 actions 中不能修改 state 的数据,所以,如果确实需要将 actions 结果保存到 state,那么我们的解决方案:
- actions 中调用 mutations 的方法,同时将数据传递给 mutations;
- mutations 中接收到数据后,修改 state。
示例代码:
import api from '@/api';// 创建仓库实例对象export default new Vuex.Store({state: {studentsData: []},mutations: {SET_STUDENTS_DATA(state, payload) {// 接收到 action 传递的方法后,用来修改 statestate.studentsData = payload;}},actions: {async getStudentsAsync(context) {const res = await api.students.get();if(res.code) {// actions 中调用 mutations 的方法context.commit('SET_STUDENTS_DATA', res.data.rows);}}}})
2、将 actions 结果返回到组件
import api from '@/api';// 创建仓库实例对象export default new Vuex.Store({actions: {async getStudentsAsync(context) {const res = await api.students.get();return res}}})
export default {methods: {getStudents () {// 组件中调用 actionsconst res = this.$store.dispatch('students/getStudentsAsync')},}
