所谓插件, 其实就是一个在全局声明的组件, 这里, 我们集中封装, 全局引入, 从而便于管理, 也能有效地提升开发效率和加载性能.
方法就是: 将这个插件的逻辑封装成一个对象, 最后将 install 编写业务代码暴露给 vue 对象, 也就是, 要公开一个 install 方法 (开发插件官方文档 https://cn.vuejs.org/v2/guide/plugins.html ). 这里, 以接口请求文档为例, 一起探讨学习下.
- 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)
- }
- 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
- }
- 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()
- })
- },
- }
- }
来源: http://www.qdfuns.com/article/25669/12e1f7a9c4c0800b609c07bb01e98729.html