〖Vue〗小知识- Vuex使用axios异步请求数据

1,145 阅读1分钟

小知识,大挑战!本文正在参与“程序员必备小知识”创作活动。

前文我们学习 Vuex 的初步使用及同步(mutations)和异步(Action-dispatch)修改存储数据, 这里都没有用到发起请求向后端请求数据; 本文学习的就相当于实际工作中项目开发的相关内容. 通过 axios 向后端发起请求, 将请求到的数据存到 Vuex Store 中, 在页面中通过特定接口调用使用数据.

Vuex 是什么

Vuex 官方文档: vuex.vuejs.org/zh/

Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。

同步和异步

  1. Vuex 同步改数据 mutations

    mutations 里面存的是同步改数据的方法: 通过 commit 调用这里面的相关方法函数

  2. Vuex 异步改数据 Action

    Action 里面存放的是异步改数据的方法: 通过 dispatch 调用这里面的相关方法函数

    Action 函数接受一个与 store 实例具有相同方法和属性的 context 对象,

Vuex 通过 axios 异步请求数据

接上文, 上文演示了 异步/同步 的加减 的代码, 都没有用动态的数据(没有从后端请求数据), 这里学习异步获取数据的几个步骤:

读取数据: this.$store.state.变量

首先在 Store 中将请求数据方法等定义好: 里面标注好了相关的步骤 1 2 3 4

// src/store/index.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)

// 这里引入 axios 用于向后端请求数据
import axios from 'axios'

var store = new Vuex.Store({
  state: {
    num: 10001,
    users: [], /// 步骤 1:  在这里定义两个变量, 用于存放请求到的数据
    goods: [], /// 步骤 1:
    /// 步骤 2 在 下面 App.vue 中
  },

  mutations: {
    changeNum(state, p) {
      // 同步更改数据
      state.num += p
    },
    /// 步骤 4:
    /// 这里的 obj 为传递过来的数据对象: `obj.type` 不是 users 就是 goods
    /// obj.list 获取的是列表的数据
    getListSync(state, obj) {
      state[obj.type] = obj.list
    },
  },
  actions: {
    // 异步更改数据
    asyncChangeNum(context, p) {
      setTimeout(() => {
        context.commit('changeNum', p)
      }, 1500)
    },
    // 步骤 3: 定义请求接口 方法函数
    getList(context, type) {
      axios.get('http://localhost:9000/' + type).then((res) => {
        console.log(context) /// 上下文 this
        context.commit('getListSync', {
          list: res.data,
          type,
        })
      })
    },
  },
})
console.log(store.state) // { num: 10001 }
export default store
  1. 然后在模板使用数据:

// App.vue

<template>
  <div id="app">
    <router-link to="/users">users</router-link>
    <router-link to="/goods">goods</router-link>
    <router-view></router-view>
  </div>
</template>

<script>
  export default {
    name: 'App',
    created() {
      /// 请求数据一般可以在 created 和 mounted 中发起请求
      this.$store.dispatch('getList', 'users') /// 步骤 2:
      this.$store.dispatch('getList', 'goods')
    },
    computed: {
      // computed 计算属性, 是在 HTML DOM 加载后马上执行的!
    },
    methods: {
      inc(p) {
        this.$store.commit('changeNum', p)
      },
      asyncinc(p) {
        this.$store.dispatch('asyncChangeNum', p)
      },
    },
  }
</script>

参考 官方文档