把axios封装为vue插件使用 (2)

封装成 Vue 插件

// 导入所有接口 import apiList from './interface' const install = Vue => { if (install.installed) return; install.installed = true; Object.defineProperties(Vue.prototype, { // 注意哦,此处挂载在 Vue 原型的 $api 对象上 $api: { get() { return apiList } } }) } export default install 使用

到此为止,万事俱备就差用了,在 mian.js 中做如下操作:

import api from './http/index' Vue.use(api) // 此时可以直接在 Vue 原型上调用 $api 了

在 vue 中使用

// List.vue ... this.$api.list(id).then(res => { if (res.rc === 0) { this.pageList = res.data.item } else { this.$Message.info(res.desc); } }) .catch(error => { this.$Message.info(error); }) ... 总结

以上二次封装较为全面,基本完成了我们之前的需求

在错误的处理上还需要与后端协定好返回值,做具体的约定

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wpzxws.html