vuex 開發 測試 生產環境 配置axios

1、vue2使用 vue-cli安裝的項目 config目錄下面都有 dev.env.js/test.env.js/prod.env.js文件,做相應的修改,添加API_ROOT

module.exports = merge(prodEnv, {
  NODE_ENV: '"development"',
  API_ROOT: '"http://www.eastgrain.cn"'
})

2、src下面添加api目錄添加api.js文件

import axios from 'axios'

// 創建配置
const Axios = axios.create({
  baseURL: process.env.API_ROOT,
  timeout: 20000,
  headers: {
    'Content-Type': 'application/json'
  }
})

// request 攔截器 請求開始顯示loading等等
Axios.interceptors.request.use((config) => {
  console.log(config, 'config axios配置')
  // 顯示loading...
  return config
}, (error) => {
  return Promise.reject(error)
})

// response 攔截器
Axios.interceptors.response.use((response) => {
  console.log(response, 'axios response配置')
  // 這裏可以做處理,response.data.code 錯誤碼不同顯示不同錯誤信息
  return response.data
}, (error) => {
  return Promise.reject(error)
})
export default Axios

3、在文件中調用

import Axios from '@/api/api'
methods: {
    // 訪問接口
    getFormData () {
      Axios.post('customer/modifyUserInfo.json', {phone: 15001209233}).then((success) => { console.log(success)// 這裏可以出發vuex中的mutations、actions來修改vuex state中的數據 }).then((err) => { console.log(err) })
    },
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章