所謂插件,其實就是一個在全局聲明的組件,這裏,我們集中封裝,全局引入,從而便於管理,也能有效地提升開發效率和加載性能。
方法就是:將這個插件的邏輯封裝成一個對象,最後將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()
})
},
}
}