Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

The organization of Api in Vue project and the operation of returning data processing

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly introduces "the organization of Api in the Vue project and the operation of returning data processing". In the daily operation, I believe that many people have doubts about the organization of Api in the Vue project and the operation of returning data processing. Xiaobian consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts about "the organization of Api in the Vue project and the operation of returning data processing". Next, please follow the editor to study!

All the Api configurations in the project are placed in one file, which is easy to find and modify. The version of Api is read from the configuration file (config.js) and is composed of apiPrefix + url.

In the configuration file, Api is configured in the way of Http request url. By default, GET can not be written, the request method is in uppercase, and the dynamic parameters are in the form of placeholder.

/ / services/api.jsexport default {login: 'POST / login', logout:' / logout', queryUser:'/ user/:id'}

Then you need a method to parse the above Api configuration

/ / services/index.jsimport request from'.. / utils/request'import api from'. / api'const gen = params = > {let url = params let method = 'GET' const paramsArr = params.split ('') if (paramsArr.length = 2) {method = paramsArr [0] url = paramsArr [1]} return data = > {return request ({url, data, method})} const apiFunc = {} for (const key in api) {apiFunc [key] = gen (API [key])} export default apiFunc

The request in the above code is the method exposed after encapsulating axios. The code is as follows:

/ / utils/request.jsimport axios from 'axios'import store from'.. / store'import {apiPrefix} from'. / config'import {Message, MessageBox} from 'element-ui'let cancelconst CancelToken = axios.CancelTokenconst service = axios.create ({baseURL: apiPrefix, timeout: 3000 CancelToken: new CancelToken (c = > cancel = c)}) service.interceptors.response.use (response = > {const resType = response.config.responseType const res = response.data / / binary file if (resType & & resType! = = 'json') {const filename= response.headers [' content-disposition'] .split ('filename=') [1] return {filename Blob: res}} if (res.code! = = 200) {/ / invalid login if (res.code = 401) {let timer = null / / cancel subsequent requests cancel (res.msg) / / update store and localStorage status store.commit ('user/RESET_LOGIN_STATE', false) MessageBox.confirm (' login is invalid Please log in again', 'prompt', {confirmButtonText:'OK', showClose: false, showCancelButton: false, type: 'warning'}) .then (() = > {clearTimeout (timer) reload ()}) timer = setTimeout (reload, 1000)} const errMsg = res.msg |' Server returned error 'popupMsg (errMsg) return Promise.reject (errMsg)} return res} Error = > {/ / timeout if (error.message.includes ('timeout')) {const errMsg =' network request timeout Please retry 'popupMsg (errMsg) cancel (errMsg)}) function reload () {_ window.location.href = `${_ window.location.origin} / # / login` _ window.location.reload ()} function popupMsg (msg, sec = 5000) {Message ({message: msg, type:' error', duration: sec})} export default service

In the process of encapsulation, it deals with the network request timeout, the situation that the back end directly returns the binary file when downloading the table data, and cancels the subsequent interface request after the login fails.

Vuex is basically used in the development of background management system projects. In the actual development process, the module is usually divided according to function, and the method with side effects is injected directly through mapActions in the xx.vue file.

/ / store/common.jsimport service from'.. / services'const actions = {async login (data) {const res = await service.login (data) return Promise.resolve (res)}} export default {namespaced: true, state: {}, getters: {}, mutations: {}, actions}

In fact, in the above apiFunc method, you can call directly to return the result, so why bother here? Because sometimes the parameters of an interface need to be processed, the code is obviously redundant on each page, and it is not convenient to modify. At the same time, it will also appear to obtain the same data, but the back end of different pages will be given different interfaces. Here, you can specify which interface is needed according to the parameters.

In the encapsulated action, sometimes there is no need to return data (Promise), because you can put all the data state of the entire page in the state. After receiving the data, modify the state directly through commit a mutation, and access all the numbers in the page directly through mapState or direct this.$store.state.xx. If you want to bind the state in state to v-model, you can define get and set in computed to do so, for example:

Export default {computed: {dateType: {get () {return this.$store.state.device.dateType}, set (val) {/ / some processing, such as dynamically changing the configuration of `el-datep- icker` according to day, week and month}

It is not recommended that all the states in the page be handled in vuex in a project, except for some global states and some components that have linkage effects. Because in the current route to switch to other routes, the state data in vuex is not reset, and then cut back will find that the original data has not changed and other problems. And once there is too much nesting in defining state, it can be troublesome to reset.

There is another problem when we use echarts to dynamically change the chart drawing according to some filtering, we will find that we cannot get the latest data from mapState and getters, and we have to write a long list of this.$store.state.moduleA.moduleB.xxx.state manually. Of course, we can also use the convenient mapping method const {mapState} = createNamespacedHelper ('some/nested/module') provided by vuex, but there is a problem that once the same page references a lot of module. It involves the problem of choosing several different aliases.

Used in a project as follows:

Import {mapActions} from 'vuex'import apiFunc from'.. / services'export default {methods: {... mapActions ('common', [' login']), async onLogin () {const params = {} const res = await apiFunc.login (params)}

Note that when using async/await, if the outer error is not caught, it is best to add a layer of try...catch... .

At this point, the study on "the organization of Api in the Vue project and the operation of returning data processing" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report