vue——統一配置axios的baseUrl和所有請求的路徑


1. 配置baseUrl

在package.json同級目錄下新建一個faceConfig.js文件

 

 faceConfig.js:

// 前端所有配置放這里
const faceConfig = () => {
  return {
    // 正式環節
    'devServer': window.location.origin + '***' //***為上下文路徑
  }
}
module.exports = faceConfig()

 

2. 在src下新建api文件夾,並在其下面新建index.js文件

 

 index.js:

const API_ROOT = require('../../faceConfig.js').devServer;
export default { 
  /**  賬號密碼登錄登出  **/
  loginIn: `${API_ROOT}/xxx`,
  logOut: `${API_ROOT}/xxx`,
  /** 數據庫  **/
  list: `${API_ROOT}/xxx`, //列表
}

 

3. 組件中使用

<template>
  <div>
        <button @click="exit">退出</button >
  </div>
</template>

<script>
  import API from '../api/index.js' //注意路徑是否正確

  export default {
    name: 'Home',
    data() {
      return {}
    },
    methods: {
      exit() {
        let _this = this,
            token = localStorage.getItem('token');
        _this.$get(`${API.logout}?token=${token}`)  //` `是模板字符串,ES2015新增的符號
          .then((res) => {
            if (res.status == 200 && res.data.code == 1) {
             ···
            } else {
              ···
            }
          })
      }
    }
  }
</script>
        

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM