vue中api统一管理

针对小型项目

无需管理的情况下

<script>
import axios from 'axios';
export default {
  methods: {
    async request() {
      let data = {}
      try {
        // host指的是请求的域名,path指的是请求的路径, data是相关的参数和请求头配置
        let res = await axios.post(`${host}${path}`, {
          data
        })
        console.log(res)
      } catch(err) {
        this.$message.error(err.message)
      }
    }
  }
}
</script>

统一api.js文件管理

将所有的api的接口信息都写在一个js文件里去维护。页面接口请求直接引入即可

在根目录下创建api文件夹,然后创建index.js

export default {
  getInfo: 'https://xxx.x.com/getinfo'
}

具体页面使用

<script>
import axios from 'axios';
import api from '@/api/index';
export default {
  methods: {
    async request() {
      let data = {}
      try {
        let res = await axios.post(api.getInfo, {
          data
        })
        console.log(res)
      } catch(err) {
        this.$message.error(err.message)
      }
      
    }
  }
}
</script>

针对非小型项目

api统一管理 + 挂载到vue实例上 + 单模块

思路:在api统一管理时,不仅仅管理请求地址,而是直接写一个request的请求方法,通过接受一些参数来实现多变性。
api/index.js

import request from '@/utils/axios'
export default {
  getInfo(params) {
    return request({
      url: '/xxx/xxx/xxx',
      method: 'post/get',
      params, // 如果是get请求的话
      data: params // 如果是post请求的话
    })
  }
}

在main.js里

import Vue from 'vue'
import App from './App.vue'
import api from '@/api/index';
Vue.prototype.$api = api;
Vue.config.productionTip = false
new Vue({
  render: h => h(App),
}).$mount('#app')

页面上得使用

<script>
import HelloWorld from './components/HelloWorld.vue'
import api from '@/api/index';
export default {
  methods: {
    async request() {
      let data = {}
      try {
        let res = await this.$api.getInfo(data)
        console.log(res)
      } catch(err) {
        this.$message.error(err.message)
      }
    }
  }
}
</script>

api统一管理 + 挂载到vue实例上 + 多模块

优点:可以在任意位置调用接口
缺点:如果接口数量足够大,挂载到vue实例上得数据过多,可能会造成性能问题
api/modules/account.js

import account from '@/utils/axios'
export default {
  getInfo(params) {
    return request({
      url: '/xxx/xxx/xxx',
      method: 'post/get',
      params, // 如果是get请求的话
      data: params // 如果是post请求的话
    })
  }
}

api/index.js

import account from './modules/account'
export default {
  account
}

在main.js里

import Vue from 'vue'
import App from './App.vue'
import api from '@/api/index';
Vue.prototype.$api = api;
Vue.config.productionTip = false
new Vue({
  render: h => h(App),
}).$mount('#app')

页面上的使用

<script>
import HelloWorld from './components/HelloWorld.vue'
import api from '@/api/index';
export default {
  methods: {
    async request() {
      let data = {}
      try {
        let res = await this.$api.account.getInfo(data)
        console.log(res)
      } catch(err) {
        this.$message.error(err.message)
      }
    }
  }
}
</script>

api统一管理 + vuex + 单模块

思路:api统一管理的方式不变,但是由挂载到vue实例上改成vuex 优点:在不挂载到vue实例的基础上可以在任何页面随意调用任何接口 缺点:为了保证在刷新页面不会报错的情况下就需要在api模块写一个接口配置,同时在store模块也需要写一次,比较繁琐。
在api/index.js的写法不变。
main.js中的相关挂载代码删除
store/index.js

import Vue from 'vue';
import Vuex from 'vuex';
import api from '@/api/index';
Vue.use(Vuex);
export default new Vuex.Store({
  action: {
    getInfo(store, params) {
      return api.getInfo(params)
    }
  }
})

在页面中

<script>
export default {
  methods: {
    async request() {
      let data = {}
      try {
        let res = await this.$store.dispatch('getInfo', data)
        console.log(res)
      } catch(err) {
        this.$message.error(err.message)
      }
    }
  }
}
</script>

当然你也可以使用mapActions

<script>
import { mapActions } from 'vuex';
export default {
  methods: {
    ...mapActions([ 'getInfo' ])
    async request() {
      let data = {}
      try {
        let res = await this.getInfo(data)
        console.log(res)
      } catch(err) {
        this.$message.error(err.message)
      }
    }
  }
}
</script>

api统一管理 + vuex + 多模块

优点:可以在页面的任何位置进行调用 缺点:新增删除修改同一个接口,需要同时维护两个文件
对于api文件而言,此时各个模式是相互独立的:api/account.js

import request from '@/utils/axios'
export default {
  getInfo(params) {
    return request({
      url: '/xxx/xxx/xxx',
      method: 'post/get',
      params, // 如果是get请求的话
      data: params // 如果是post请求的话
    })
  }
}

store/modules/account.js

import api from '@/api/account';
export default {
    namespaced: true,
    actions: {
        getInfo(store, params) {
          return api.getInfo(params)
        }
    }
}

store/index.js

import Vue from 'vue';
import Vuex from 'vuex';
import account from './modules/account';
Vue.use(Vuex);
export default new Vuex.Store({
  modules: {
      account
  }
})

在页面中

<script>
export default {
  methods: {
    async request() {
      let data = {}
      try {
        let res = await this.$store.dispatch('account/getInfo', data)
        console.log(res)
      } catch(err) {
        this.$message.error(err.message)
      }
    }
  }
}
</script>

感谢原创:https://juejin.cn/post/7084149728799096840

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,835评论 4 364
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,598评论 1 295
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,569评论 0 244
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,159评论 0 213
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,533评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,710评论 1 222
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,923评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,674评论 0 203
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,421评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,622评论 2 245
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,115评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,428评论 2 254
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,114评论 3 238
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,097评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,875评论 0 197
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,753评论 2 276
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,649评论 2 271

推荐阅读更多精彩内容