所谓插件,其实就是一个在全局声明的组件,这里,我们集中封装,全局引入,从而便于管理,也能有效地提升开发效率和加载性能。
方法就是:将这个插件的逻辑封装成一个对象,最后将install编写业务代码暴露给Vue对象,也就是,要公开一个install方法([开发插件官方文档](https://cn.vuejs.org/v2/guide/plugins.html))。这里,以接口请求文档为例,一起探讨学习下。接口请求文档:api > action > crownpin.js
import fetch from '../axios'
import {crownpin} from '../port_url'
import store from '../../store'
export function toLogin(params) {
store.commit('openLoading')
return fetch.$ajax('POST', crownpin.loginurl, params);
}
export function loginOld(params) {
store.commit('openLoading')
return fetch.$ajaxOld('POST', crownpin.loginOldUrl, params);
}
//获取销售顾问
export function getAccount(params,hideLoad){
if(!hideLoad){
store.commit('openLoading')
}
return fetch.$ajax('GET', crownpin.getAccount, params);
}
//线索管理
export function clue(params,hideLoad){
if(!hideLoad){
store.commit('openLoading')
}
return fetch.$ajax('GET', crownpin.clue, params);
}
//设置 在售车辆管理 获取展厅车型
export function carManageShowCars(params,hideLoad){
if(!hideLoad){
store.commit("openLoading")
}
return fetch.$ajax('GET',crownpin.carManageShowCars,params)
}
将 api 挂载到 Vue.prototype 上,导出 install 函数
api > action > index.js
import * as crownpin from './crownpin'
import * as common from './common'
import {POST,GET,AJAX} from './common'
let apiObj={crownpin,common,POST,GET,AJAX};
const install = function (Vue) {
//如果安装过就忽略
if (install.installed) {
return
}
//否则就安装
install.installed = true;
Object.defineProperties(Vue.prototype, {
$fetch: {
get() {
return apiObj
}
}
})
}
export default {
install
}
main.js
import Vue from 'vue'
import api from '@/api/action'
Vue.use(api)
应用:
export default {
created(){
this.init()
},
methods:{
...mapMutations(['closeLoading']),
init(){
this.$fetch.crownpin.carManageShowCars().then((res)=>{
this.closeLoading();
}).catch((res)=>{
this.closeLoading()
})
},
}
}