In the last article, we used VUE-CLI + Vant to build a mobile development template. We built a simple template suitable for H5 development, and many details were passed over. This article will show you what happens in the process of getting data from the request interface to the page (request interface, AXIOS interception, state management, exception handling, etc.).

Source code address (master branch is the latest code, this branch is 2020/06/17)

preface

Not all interfaces use VUEX state management. Not all interfaces use VUEX state management. Not all interfaces use VUEX state management. The following is a small example. This is not how projects should be managed.

The flow chart

Flow charts refer to the vuEX website

A, Dispatch.

Use mapActions to inject the actions we need in the store into the component (views\ about.vue)

import { mapActions } from "vuex";
export default {
  created() { const parameter = {id: 1} this.getSomeData(parameter); }, methods: { ... mapActions("some"["getSomeData"])}};Copy the code

Action Performs asynchronous operations

In this Action, the method that requests the interface is executed (store\modules\some.js)

async getSomeData({ commit }, parameter) {
    console.log(parameter)
    const response = await getSomeDataApi(parameter)
}
Copy the code

The AXIOS request interface through secondary encapsulation

We rewrap AXIOS to encapsulate common request interception, exception handling, request, and so on for unified operation. (api\some.js)

import { axios } from '@/utils/request'
export function getSomeDataApi(parameter) {
  return axios({
    url: '/detail',
    method: 'get',
    params: parameter
  })
}
Copy the code

Re-encapsulates AXIos under utils\request

import axios from 'axios'
import { errorCode } from './errorCode'// Create an axios instance const service = axios.create({baseURL: process.env.vue_app_API_base_URL, // API base_url timeout: // Request timeout}) const err = (error) => {err = (error) => {if (error.response) {
    if(error.response.status ! Const errorMessage = errorCode(error.response) console.log(errorMessage) const errorMessage = errorCode(error.response) console.log(errorMessage)return}}returnPromise.reject(error)} // In request interception, we can process the request header, Like all request add a token etc. Service interceptors. Request. Use (config = > {/ / const token ='token'
  // if (token) {
  //   config.headers['Access-Token'] = token // Allow each request to carry a customized token. Please modify the token according to the actual situation.returnConfig}, err) // Return data intercepting, we can do some small processing, such as the back end of all the interface return data is this type :{data: {... }}, then we can put the data in this layer to filter out the service. The interceptors. Response. Use ((response) = > {return response.data
}, err)


export {
  service as axios
}

Copy the code

In the code above, there is a baseURL whose value can be obtained from the.env file, which acts as a common address for all requests. For example: all the interfaces need to add a/API for the background interface to do forwarding, we definitely do not add a/API in front of all the interfaces, that is too cumbersome and laborious, this time we can use baseURL.

4. Get the returned data

If we want to get results immediately after the data is retrieved, we can pass a callback argument from the Action to the component.

1, modify some. vue, add callback parameter

import { mapActions } from "vuex";
export default {
  created() {
    const parameter = {id: 1}
    this.getSomeData(parameter);
    this.doSomeCallback({
      parameter,
      callback: res => {
        console.log('Here's the data that callback comes back from actions'+ res) } }); }, methods: { ... mapActions("some"["getSomeData"."doSomeCallback"])}};Copy the code

2, modify store\modules\some.js

async doSomeCallback({ commit }, { parameter, callback }) 
    const response = await getSomeDataApi(parameter)
    if (callback) callback(response)
 }
Copy the code

Fifth, the Commit

After receiving the data returned by the interface in the Action, we can perform Mutation by using the commit method. Modify the store \ modules \ some js

import { getSomeDataApi } from '@/api/some'

const mutations = {
  setSomeData: (state, data) => {
    console.log(data)
  }
}

const actions = {
  async getSomeData({ commit }, parameter) {
    console.log(parameter)
    const response = await getSomeDataApi(parameter)
    commit('setSomeData', response)
  },
  async doSomeCallback({ commit }, { parameter, callback }) {
    console.log(parameter)
    const response = await getSomeDataApi(parameter)
    commit('setSomeData', response)
    if (callback) callback(response)
  },
}
Copy the code

Six, Mutate

The only way to change the state in Vuex’s store is to commit mutation. After we get the data, we modify the value in state. The final code for store\modules\some.js

import { getSomeDataApi } from '@/api/some'

const state = {
  someData: ' '
}

const mutations = {
  setSomeData: (state, data) => {math.random () state.someData = data? data : Math.random() } } const actions = { async getSomeData({ commit }, parameter) { console.log(parameter) const response = await getSomeDataApi(parameter) commit('setSomeData', response)
  },
  async doSomeCallback({ commit }, { parameter, callback }) {
    console.log(parameter)
    const response = await getSomeDataApi(parameter)
    commit('setSomeData', response)
    if (callback) callback(response)
  },
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
Copy the code

Seven, Render

After the value in state is changed, the page will be updated if the value of the binding binding in our component changes. Modify Some. Vue.

import { mapState } from "vuex"; computed: { ... mapState("some"["someData"])
}

<div class="about">
    {{someData}}
</div>
Copy the code

Our final code for some.vue looks like this

<template>
  <div class="about">
    <router-link to="/">Home</router-link>
    <Button type="primary" @click="doSomeCallback"</Button> {{someData}} </div> </template> <script> import {mapState, mapActions} from"vuex";
import { Button } from "vant";
exportdefault { computed: { ... mapState("some"["someData"])},created() {
    const parameter = { id: 1 };
    this.getSomeData(parameter);
    this.doSomeCallback({
      parameter,
      callback: res => {
        console.log("Here's the data from actions callback." + res);
      }
    });
  },
  methods: {
    ...mapActions("some"["getSomeData"."doSomeCallback"])
  },
  components: {
    Button
  }
};
</script>
<style lang="less">
.about {
  height: 100vh;
  font-size: 14px;
}
#detail {
  font-size: 14px;
}
</style>
Copy the code

Points to note when using VUEX

Advantages: If all interfaces are vuEX managed, there is a fixed flow, which is clear and easy to maintain.

Disadvantages: Due to the excessive number of components and data, the data in VUEX will become larger and the memory footprint will become larger.

Vuex is commonly used in the following situations: Multiple components use the same interface data (such as background management of a drop-down box data), application status management (such as H5 in-application storage of user data), etc.

For details, please refer to a diagram to figure out what kind of data should be stored in Vuex. Should I Store This Data in Vuex — When Should I use Vuex?

To borrow someone else’s picture:

conclusion

The above flow of request interface to page updates shows you how to manage AXIOS requests and VUex in a project. Due to my poor writing style, there may be some confusion in the article, I hope you can understand. (Source code at the beginning of the article)

Thank you for reading, if you have any modifications or suggestions, please feel free to put forward.