Vue building project (1): use of axios

1. The project uses axios
1. Install axios

npm install --save axios

2. Axios secondary encapsulation
The main purpose of secondary encapsulation of axios is to set up the request interceptor (do something before the request is sent) and the response interceptor (do something after the data is returned). 2.1 Create a folder under
src Specially used to install all requested js files src/api/request.js
request.js

//对于axios进行二次封装
import axios from "axios";
//底下的代码也是创建axios实例
let requests = axios.create({
    
    
  //基础路径
  baseURL: "/local",//对应vue.config文件里面的proxy代理
  //请求不能超过5S
  timeout: 5000,
});
 
//请求拦截器(可以在请求发出去之前,做一些事情)
requests.interceptors.request.use((config) => {
    
    
config.headers['Authorization'] = getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
  return config;
}, error => {
    
    
  Promise.reject(error)
}))
 
//响应拦截器(在数据返回之后,做一些事情)
requests.interceptors.response.use(
  (res) => {
    
    
    //响应成功
    return res.data;
  },
  (err) => {
    
    
    //响应失败
    alert("服务器响应数据失败");
  }
);
export default requests;

3. Configure the proxy server: Configure in vue.config (devServer.proxy part)
vue.config complete configuration reference document bottom link


const CompressionPlugin = require('compression-webpack-plugin')

const name =  '配电监测' // 网页标题

// vue.config.js 配置说明
//官方vue.config.js 参考文档 https://cli.vuejs.org/zh/config/#css-loaderoptions
// 这里只列一部分,具体配置参考文档
module.exports = {
    
    
  // 部署生产环境和开发环境下的URL。
  // 默认情况下,Vue CLI 会假设你的应用是被部署在一个域名的根路径上
  // 例如 https://www.ruoyi.vip/。如果应用被部署在一个子路径上,你就需要用这个选项指定这个子路径。例如,如果你的应用被部署在 https://www.ruoyi.vip/admin/,则设置 baseUrl 为 /admin/。
  // publicPath: process.env.NODE_ENV === "production" ? "/" : "/",
  // 在npm run build 或 yarn build 时 ,生成文件的目录名称(要和baseUrl的生产环境路径一致)(默认dist)
  outputDir: 'dist',
  // 用于放置生成的静态资源 (js、css、img、fonts) 的;(项目打包之后,静态资源会放在这个文件夹下)
  assetsDir: 'static',
  // 是否开启eslint保存检测,有效值:ture | false | 'error'
  // lintOnSave: process.env.NODE_ENV === 'development',
  lintOnSave: false,
  // 如果你不需要生产环境的 source map,可以将其设置为 false 以加速生产环境构建。
  productionSourceMap: false,
  // webpack-dev-server 相关配置
  devServer: {
    
    
    host: '0.0.0.0',//指定使用的ip地址,默认为localhost,如果使用'0.0.0.0'则可以被外部访问
    port: '8080',
    open: true,
    proxy: {
    
    
      // detail: https://cli.vuejs.org/config/#devserver-proxy
      'local': {
    
    
         target: `http://10.100.10.54:18080`,//测试服
        //target: `https://icp.minexiot.com/prod-api`,//正式服
        // target: `http://172.16.201.59:18080`,
        changeOrigin: true,
       // pathRewrite: {
    
    
       //  ['^' + process.env.VUE_APP_BASE_API]: ''
       // }
      }
    },
    disableHostCheck: true
  },
  css: {
    
    
    loaderOptions: {
    
    
      sass: {
    
    
        sassOptions: {
    
     outputStyle: "expanded" }
      }
    }
  },
  configureWebpack: {
    
    
    name: name,
    resolve: {
    
    
      alias: {
    
    
       '@': path.resolve(__dirname, 'src')
      }
    },
    plugins: [
      // http://doc.ruoyi.vip/ruoyi-vue/other/faq.html#使用gzip解压缩静态文件
      new CompressionPlugin({
    
    
        cache: false,                   // 不启用文件缓存
        test: /\.(js|css|html)?$/i,     // 压缩文件格式
        filename: '[path].gz[query]',   // 压缩后的文件名
        algorithm: 'gzip',              // 使用gzip压缩
        minRatio: 0.8                   // 压缩率小于1才会压缩
      })
    ],
  },
  chainWebpack (config) {
    
    
    config.plugins.delete('preload') // TODO: need test
    config.plugins.delete('prefetch') // TODO: need test

    // set svg-sprite-loader
    config.module
      .rule('svg')
      .exclude.add(resolve('src/assets/icons'))
      .end()
        }
      )
  }
}

4. Use
Create a new folder under the api file to facilitate the management interface src/api/common/index.js

import request from '@/api/request' 

// 获取所有下拉菜单type
export const getType = () => {
    
    
  return request({
    
    
    url: '/selects/types',
    method: 'get',
  })
}

// 根据type获取下拉列表数据
export const getTypeOption = (type) => {
    
    
  return request({
    
    
    url: '/selects',
    method: 'get',
    params: {
    
    type:type}
  })
}

vue page uses:

import {
    
     getTypeOption } from "@/api/common/index";//引入

getTypeOptions() {
    
    
      getTypeOption("OperationAction").then((res) => {
    
    
        if (res.code == 200) {
    
    
          //成功操作
        }
      });
    },

Reference/Others:
Introduction of axios in VUE project
Use of axios in VUE
Vue.conifg.js complete configuration item
Use of svg in Vue project

Guess you like

Origin blog.csdn.net/Web_Notes/article/details/131223783