一、定义 actions 方法

  1. export default new Vuex.Store({
  2. actions: {
  3. async getStudentsAsync(context) {
  4. const res = await api.students.get();
  5. console.log('后端返回的结果:', res);
  6. }
  7. }
  8. })

二、调用 actions 方法

组件中调用 actions 的方法:

  1. export default {
  2. created() {
  3. // 调用组件自己的 methods
  4. this.getStudents();
  5. },
  6. methods: {
  7. getStudents() {
  8. // 组件中调用 actions
  9. this.$store.dispatch('getStudentsAsync');
  10. }
  11. }
  12. }

三、将 actions 结果交给组件

要将 actions 的请求结果交给组件,有两种方式:

  1. 把请求结果保存到 state,组件从 state 中获取请求结果;
  2. 把请求结果通过 return 返回,组件中直接接收 actions 方法的返回值;

我们依次来看一下这两种用法:

1、将 actions 结果保存到 state

因为 actions 中不能修改 state 的数据,所以,如果确实需要将 actions 结果保存到 state,那么我们的解决方案:

  1. actions 中调用 mutations 的方法,同时将数据传递给 mutations;
  2. mutations 中接收到数据后,修改 state。

示例代码:

  1. import api from '@/api';
  2. // 创建仓库实例对象
  3. export default new Vuex.Store({
  4. state: {
  5. studentsData: []
  6. },
  7. mutations: {
  8. SET_STUDENTS_DATA(state, payload) {
  9. // 接收到 action 传递的方法后,用来修改 state
  10. state.studentsData = payload;
  11. }
  12. },
  13. actions: {
  14. async getStudentsAsync(context) {
  15. const res = await api.students.get();
  16. if(res.code) {
  17. // actions 中调用 mutations 的方法
  18. context.commit('SET_STUDENTS_DATA', res.data.rows);
  19. }
  20. }
  21. }
  22. })

2、将 actions 结果返回到组件

  1. import api from '@/api';
  2. // 创建仓库实例对象
  3. export default new Vuex.Store({
  4. actions: {
  5. async getStudentsAsync(context) {
  6. const res = await api.students.get();
  7. return res
  8. }
  9. }
  10. })
  1. export default {
  2. methods: {
  3. getStudents () {
  4. // 组件中调用 actions
  5. const res = this.$store.dispatch('students/getStudentsAsync')
  6. },
  7. }