首页 > 其他分享 >基于Vue 的axios简单封装

基于Vue 的axios简单封装

时间:2024-04-13 21:44:06浏览次数:18  
标签:function arr axios 封装 name url ob Vue data

在static/mock下建一个模拟数据文件 json1.json

{
  "a1": 123,
  "a2": 567
}

在文件目录下新建 src/utlis/http.js


//src/utlis/http.js
import axios from "axios";
export default (function() {
  function qa(arr) {
    let _iqaob = new _iqa(),
      _urlarr = arr || [];
    arr.forEach((item, i) => {
      let _name = qa.getPathname(_urlarr[i]);
      (function(url) {
        _iqaob[_name] = function(ob) {
          _iqaob.sendMes.call(_iqaob, url, ob);
        };
      })(_urlarr[i]);
    });

    return _iqaob;
  }
  function _iqa() {
    this._vueob = {};
    this.statue = 0;
  }
  // 发送请求
  _iqa.prototype.sendMes = function(url, ob) {
    console.log("console", this, url, ob);
    let self = this,
      _url = url || "",
      _ob = ob || {},
      _type = _ob.type || "get",
      _data = _ob.data || {},
      _isblock = _ob.isblock || true, //是否阻塞()
      callback =
        _ob.callback ||
        function() {
          console.log("callback is  undefined");
        };

    let status = {
      get: function() {
        let _quary = qa.qs(_data);
        axios.get(_url + _quary).then(function(res) {
          const _name = qa.getPathname(_url);
          const result = callback.call(self._vueob, res);
          if (result) {
            self._vueob[_name] = result;
          } else {
            self._vueob[_name] = res.data;
          }
        });
      },
      post: function() {},
      put: function() {},
      delete: function() {}
    };

    //这里判断控制是否可以重复提交
    if (self.statue == 0 || !_isblock) {
      if (_isblock) {
        self.statue = 1;
      }
      status[_type]();
    } else {
      status[_type]();
    }
  };

  _iqa.prototype.v = function(vueob) {
    this._vueob = vueob;
    return this;
  };

  //获取接口名
  qa.getPathname = function(url) {
    let _arr = url.split("/"),
      _name = _arr[_arr.length - 1],
      _newname = _name.split(".")[0];
    return _newname;
  };

  //参数序列化
  qa.qs = function(data) {
    let _str = "",
      _len = 0;
    if (JSON.stringify(data) != "{}") {
      _str += "?";
    }
    for (var item in data) {
      if (_len != 0) {
        _str += "&";
      }
      _str += item;
      _str += "=";
      _str += data[item];
      _len++;
    }
    return _str;
  };

  return qa;
})();

//main.js
const files = require.context("../static/mock", true, /\.json$/);
let arr = [];
files.keys().forEach(key => {
  arr.push("./static/mock/" + key.replace(/(\.\/)/g, ""));
});

// * Axios
import http from "./utils/http.js";
Vue.prototype.http = http(arr);
console.log("console", Vue.prototype.http);

在 HelloWorld.vue 文件中

 //HelloWorld.vue 
<template>
  <div class="hello">
    <pre>{{ json1 }}</pre>
    <!-- <Com1/>
    <Com2/> -->
    <router-link to="./com1">com1</router-link>
    <router-link to="./com2">com2</router-link>

    <!-- 按钮根据value -->
    <div v-permission="'10'">
      <button>权限1</button>
    </div>
    <div v-permission="'5'">
      <button>权限2</button>
    </div>

    <router-view />
  </div>
</template>


<script>
export default {
  name: "HelloWorld",
  data() {
    return {
      json1: ""
    };
  }, 
  mounted() {
  //这里调用axiox
    this.http.v(this).json1({
      data: { a: 1, b: 1 },
      callback: function(res) {
       return res.data.a1
      }
    });
  },
  methods: {}
};
</script>
<style scoped>
h1,
h2 {
  font-weight: normal;
}
ul {
  list-style-type: none;
  padding: 0;
}
li {
  display: inline-block;
  margin: 0 10px;
}
a {
  color: #42b983;
}
</style>

标签:function,arr,axios,封装,name,url,ob,Vue,data
From: https://www.cnblogs.com/whoelse/p/18133420

相关文章

  • vue 响应性代码demo
    <!DOCTYPEhtml><htmllang="en"><head><metacharset="UTF-8"><metahttp-equiv="X-UA-Compatible"content="IE=edge"><metaname="viewport"content="width=device......
  • Java基础知识篇02——封装
    大家好,我是白夜,今天给大家聊聊面向对象的三大特征——封装一、包(package)1.1、包的引入先来看看我们之前写的代码结构以上代码存在的问题所有类写在一个目录下面,非常难管理,因为以后项目不可能只有这么几个类,当类数量很大的时候,就不容易管理了。不能写同名但是不同需求的类......
  • node笔记1:vue+node+mongodb+studio 3T创建登录模块
    1.创建node项目:expressnodenpmipackage.json修改如下代码,便于每次修改代码都可以刷新页面:"scripts":{"start":"node-dev./bin/www"}2.如果配合node设置反向代理;3.添加mongoose模块提供数据库信息:npmimongoose--save4.以登录功能模块为例,项目文件如下:model......
  • VUE2.0版本学习笔记
    VUE2.0版本学习笔记脚手架安装npminstall-g@vue/clivuecreatevue2-practice#选择2.0版本如果执行中遇到错误,yarn的错误certificatehasexpired则执行yarncachecleanyarnconfigsetstrict-sslfalsecdvue2-practicenpmrunserve#初学者建议安装vsco......
  • Springboot2+vue2整合项目
    前端https://blog.csdn.net/m0_37613503/article/details/128961447数据库1.用户表CREATETABLE`x_user`(`id`int(11)NOTNULLAUTO_INCREMENT,`username`varchar(50)NOTNULL,`password`varchar(100)DEFAULTNULL,`email`varchar(50)DEFAULTNULL,`......
  • vue+element ui el-form 阻止表单输入框按回车刷新页面
    表单只有一个元素的时候,回车会触发页面刷新,加上下面这个属性可以解决这个问题@submit.native.prevent给某个el-input添加回车键监听@keyup.enter.native="onSearch"<el-form:model="filters"@submit.native.prevent><el-form-item>......
  • vue tsx 原生属性报错解决方案
    当前依赖├──@vitejs/[email protected]├──@vitejs/[email protected]├──[email protected]├──[email protected]├──[email protected]├──[email protected]├──[email protected]└──[email protected]方法0官方方法,修改tsconfig.json,截止写文章时,这个......
  • 清除vue默认样式
    1:引入reset.scss/***ENGINE*v0.2|20150615*License:none(publicdomain)*/*,*:after,*:before{box-sizing:border-box;outline:none;}html,body,div,span,applet,object,iframe,h1,h2,h3,h4,h5,h6,p,blockquote,pre,a,abbr......
  • vue一键复制
    vue一键复制copyToClipboard(textToCopy){//navigatorclipboard需要https等安全上下文if(navigator.clipboard&&window.isSecureContext){//navigatorclipboard向剪贴板写文本returnnavigator.clipboard.writeText(textToCopy);......
  • 设置vue项目运行后,自行打开浏览器。src起别名
    1:设置vue项目运行后,自行打开浏览器找到package.json配置文件 2:src起别名,这样就可以直接找到文件路径,不需要../../的这些繁琐操作。意思直接使用@符号就代表src目录1):在vite.config.ts修改import{defineConfig}from'vite'importvuefrom'@vitejs/plugin-vue'//引入n......