日常总结之Vue项目封装axios-ajax请求文件(万金油版)

日常总结之Vue项目封装axios-ajax请求文件(万金油版)

在开发过程中我们编辑完页面,就需要把假数据换成后台数据,便需要与后端实现联调,在普通项目,一般我们都是用ajax的方式去请求后台数据,而当我们用Vue开发的时候,Vue提供了基于Promise的HTTP库,可以用在浏览器和Node.js之中,下面看代码~

这是在最近项目一个vue文件里面template代码块的一个v-for循环,对于vue文件和v-for还不了解的可以先看下vue官方文档

 <div v-for="(item,index) in datalist" :key="index">
            <el-submenu :index="index+'submenu'" v-if="item.children && item.children.length>0">
              <template slot="title">
                <i :class="item.icon"></i>
                <span slot="title">{{!collapse?item.title:''}}</span>
              </template>
              <el-menu-item-group>
                <el-menu-item
                  :index="childrenItem.path"
                  v-for="(childrenItem,childrenIndex) in item.children"
                  :key="childrenIndex"
                >{{childrenItem.title}}
              </el-menu-item>
              </el-menu-item-group>
            </el-submenu>
            <el-menu-item :index="item.path" v-else>
              <i :class="item.icon"></i>
              <span slot="title">{{item.name}}</span>
            </el-menu-item>
          </div>

以下是vue页面的data

 data () {
       return {
         datalist: this.$store.state.authority.memu
       }
  },

以上用了vuex的全局变量,以下是store的index.js部分代码,也就是所谓的假数据。

npm install vuex --save //安装依赖 在命令行

创建store文件夹,在里面创建index.js,并引入以下

import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
  /* eslint-disable */
    state: {
      loading: false,//展示加载中
       userInfo: {
       nickname: '',
       token: '',
       authority: {}
        },
       authority: {
         memu: [
           {
            name: '首页',
            path: '/PageOne',
            icon: 'el-icon-s-home',
            meta: { title: '数据查看' }
           },
           {
            name: '财务报表',
            icon: 'el-icon-s-data',
            path: '/Finance',
            children: []
           }
         ]
       },
       mutations: {
        // mutations下的方法第一个参数是固定state
         // 第二个参数是传进来的参数
       changeLoading(state, loading) {
               state.loading = loading;
          },
    }
})

main.js

import store from './store/index.js'
import Vuex from 'vuex'
Vue.use(Vuex)
new Vue({
...
  store,
...
})

这样子就能形成一个假数据了,接下里我们就要编辑一个万能ajax.js文件来封装各种请求,并替换假数据。ajax.js一般放在src的下级文件夹utils下
请看注释

import axios from 'axios'
//引入axios
import {
  Loading
  //引入element的等待组件,记得在main引入elementui
} from 'element-ui';
import {
  Message
  //引入element的提示消息组件
} from 'element-ui';
import store from '@/store'
引入vuex
const BASE_URL = process.env.NODE_ENV == 'development' ? '/apis' : process.env.API_ROOT //自动配置环境
//这里的apis就是域名,config可以设置
axios.interceptors.request.use(config => {
  // 在发送请求之前做些什么,一般都是在这里加入token,token也是验证一个用户的身份证,在登陆的时候会用用户名和密码像后端获取,后端返回token做身份证,这个地方可以让以后的请求都自动加入token在头部
  let userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
  let token = userInfo.token || ''
  config.headers['Access-Token'] = token//添加到请求头
  //以上是在浏览器获取token值,后端返回token实在login登陆界面就缓存在浏览器的呢,这边是获取,可以上网查下localStorage
  return config;
}, error => {
  // 对请求错误做些什么
  return Promise.reject(error);
});
let that = this;
//this指向
var com = {
//声明个对象com
  host: {
//这里就是你放接口的地方,一个对应一个借口,可以简单说就是路径
    login: 'V1/home/login', //登录
    logout: 'V1/home/logout', //退出登录

    guanliadd: 'V1/home/mp/add', //添加公众号
    guanliedit: 'V1/home/mp/edit', //编辑公众号
    guanlidel: 'V1/home/mp/del',  //删除公众号
    guanlilist: 'V1/home/mp/list', //获取公众号列表

    indexqrcode: 'V1/home/qrcode', //主页获取二维码
    indexscan: 'V1/home/scan', //登录是否成功

    Recordfans:'V1/home/fans'//列表
  },
  request: function (option) {
  //这个就是发送请求了request
    let loading = true;
    //默认是true,也就是需要的
    // 下面判断是否需要加载loading
    option.noLoading ? loading = false : ''
  //三目运算,如果不需要有等待特效,请求参数要加个onloading,如果有这个参数就运行loading = false
    return new Promise(function (resolve, reject) {
    //放回值,也就是请求的结果
      let url = BASE_URL + option.url;
//字符串拼接,域名+接口
      //执行异步ajax请求
      let toast1 = null;
      if (loading) {
      //如果loading为true,运行
        store.commit('changeLoading', true)
        //调用 changeLoading(state, loading) {state.loading = loading;}改变变量
        toast1 = Loading.service({
          lock: true,
          text: 'Loading',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
      }
      //下面是判断请求是post还是get
      if (option.method == 'POST') {
        axios.post(url, option.params, option.other).then((res) => { 
        //post和get方法传params方式有些不一样,get需嵌套多一个(params:{})

            loading ? toast1.close() : '';
            store.commit('changeLoading', false)
            //继续调用changeLoading方法,改变变量,实现等待的效果
            //res.data.errcode是状态码,根据状态码返回对应的结果或失败原因
          if (res.data.errcode == 0) {
            resolve(res.data)
            option.ok(res.data)
            //这里定义了ok方法,也就是成功的方法
          }
          if (res.data.errcode == 400) {
            if (option.fail) {
              option.fail(res)
            } else {
              console.log('400报错')
              Message({
                message: res.data.errmsg || '',
                type: "error"
              });
            }
          }
          if (res.data.errcode == 401) {

            window.localStorage.removeItem('token')
            window.location.href = 'http://fans.dock.xin/src'
          }
          if (res.data.errcode == 403) {
            console.log('权限不足')
            // resolve(res.data)
            // option.ok(res.data)
          }

        }).catch((res) => {
        //请求出错,调用方法改变变量,然后弹出错误
          loading ? toast1.close() : '';
          store.commit('changeLoading', false)
          reject(res)
        })
      } else {
      //下面是get请求方式
        axios.get(url, {
          params: option.params ? option.params : {}
        }).then((res) => {
          console.log(res)
          loading ? toast1.close() : '';
          store.commit('changeLoading', false)
          //和post同样的道理
          if (res.data.errcode == 0) {
            resolve(res.data)
            option.ok(res.data)
          }
          if (res.data.errcode == 400) {
            if (option.fail) {
              option.fail(res)
            } else {

              Message({
                message: res.data.errmsg || '操作失败',
                type: "error"
              });

            }
          }
          if (res.data.errcode == 401) {
            console.log('用户过期post')

            window.localStorage.removeItem('token')
            window.location.href = 'http://fans.dock.xin/src'

          }
        }).catch((res) => {

          reject(res)
          if (loading) {
            // loading ? toast1.close() : '';
            store.commit('changeLoading', false)
          }
        })
      }
    })

  }
};
export {
//导出com
  com
}

接下来我们就可以再vue文件调用ajax,并请求啦。接下来演示登录一个请求。

//导入文件
  import {
    com
  } from "@/utils/ajax";//引用com
。。。。。。
//点击事件
  submitForm(formName) {
  //这是我表单的提交按钮
        let that = this;
        let ruleForm = JSON.parse(JSON.stringify(that.ruleForm));
        //这个是获取表单的用户名密码
        this.$refs[formName].validate((valid) => {
        //element的表单校验
          if (valid) {
          //校验成功的话运行请求
            // that.$router.replace('/index')
            // console.log('密码账号是正确的')
            let url = com.host.login;//设定login接口
            com.request({
            //用我们封装的函数来请求
              url: url,
              method: "POST",
              params: ruleForm,
              //params只可以是对象,所以要用 JSON.parse(JSON.stringify(that.ruleForm));先处理
              ok: (res) => {
              // 缓存
              window.localStorage.setItem(
                "userInfo",
                JSON.stringify({
                  account : res.body.account,
                  //用户名称,主要看后端有没有传
                  token : res.body.token
                  //token,也就是身份证,后端要根据账号密码创建一个,当我们注销的时候就删除,临时身份证
                })
              );
                that.$router.push("/index");
                //这里是成功后要运行的代码,有把token放进缓存,有跳转到主页
              },
            });
          }
        })
      },

以上就是完整的vue中使用ajax请求了,你们会发现,你们只需要把ajax.js直接复制使用进你们的项目,并修改域名,api等配置,然后在你们需要的vue页面这样子调用模板。

 com.request({
              url: com.host.api,//api
              method: "POST",//请求方式
              params: ruleForm,//参数,必须json
              ok: (res) => {
              //成功要干嘛
              },
              fail:(res) => {
              //失败要干嘛
              }

            });

好啦,感谢您的认真观看,如果您对这篇文章有新的看法或有错误指出,非常欢迎您能在评论区留言,我定认真观看并回评。~~~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值