100字范文,内容丰富有趣,生活中的好帮手!
100字范文 > 对于api对接接口的全程详解(vue+ant design+api+axios).项目实战

对于api对接接口的全程详解(vue+ant design+api+axios).项目实战

时间:2021-08-19 17:38:24

相关推荐

对于api对接接口的全程详解(vue+ant design+api+axios).项目实战

编写总结不易 点赞关注收藏三连一波 哈哈哈

使用axios请求库前提

封装 axios 工具,编辑 src/api/index.js 文件

首先,我们要使用 axios 工具,就必须先安装 axios 工具。执行下面的命令进行安装

npm install axios -D

由于宿舍翻墙条件不好,这里使用 cnpm 替代

这样,我们就安装好了 axios 工具了。

一 ,

新建了一个 src/api/index.js

配置封装axios请求

// 配置API接口地址var root = '/api/v1' //写死的地址var root = '/apis'; //动态切换 配合配置文件 正常是config文件// 引用axiosvar axios = require('axios')// 自定义判断元素类型JSfunction toType (obj) {return ({}).toString.call(obj).match(/\s([a-zA-Z]+)/)[1].toLowerCase()}// 参数过滤函数function filterNull (o) {for (var key in o) {if (o[key] === null) {delete o[key]}if (toType(o[key]) === 'string') {o[key] = o[key].trim()} else if (toType(o[key]) === 'object') {o[key] = filterNull(o[key])} else if (toType(o[key]) === 'array') {o[key] = filterNull(o[key])}}return o}

/*

接口处理函数

这个函数每个项目都是不一样的,我现在调整的是适用于

/api/v1 的接口,如果是其他接口

需要根据接口的参数进行调整。参考说明文档地址:

/topic/5378720ed6e2d16149fa16bd

主要是,不同的接口的成功标识和失败提示是不一致的。

另外,不同的项目的处理方法也是不一致的,这里出错就是简单的alert

*/

function apiAxios (method, url, params, success, failure) {if (params) {params = filterNull(params)}axios({method: method,url: url,data: method === 'POST' || method === 'PUT' ? params : null,params: method === 'GET' || method === 'DELETE' ? params : null,baseURL: root,withCredentials: false}).then(function (res) {if (res.data.success === true) {if (success) {success(res.data)}} else {if (failure) {failure(res.data)} else {window.alert('error: ' + JSON.stringify(res.data))}}}).catch(function (err) {let res = err.responseif (err) {window.alert('api error, HTTP CODE: ' + res.status)}})}// 返回在vue模板中的调用接口export default {get: function (url, params, success, failure) {return apiAxios('GET', url, params, success, failure)},post: function (url, params, success, failure) {return apiAxios('POST', url, params, success, failure)},put: function (url, params, success, failure) {return apiAxios('PUT', url, params, success, failure)},delete: function (url, params, success, failure) {return apiAxios('DELETE', url, params, success, failure)}}

调整 main.js 绑定 api/index.js 文件

因为原始文件就配置得比较好,就是加上两行定义

原始是

import Vue from 'vue'import App from './App'import router from './router'Vue.config.productionTip = false/* eslint-disable no-new */new Vue({el: '#app',router,template: '<App/>',components: {App }})修改添加后import Vue from 'vue'import App from './App'import router from './router'// 引用API文件import api from './api/index.js'// 将API方法绑定到全局Vue.prototype.$api = apiVue.config.productionTip = false/* eslint-disable no-new */new Vue({el: '#app',router,template: '<App/>',components: {App }})

修改一下 src/page/index.vue 文件,将代码调整为以下代码:

<template><div>index page</div></template><script>export default {created () {this.$api.get('topics', null, r => {console.log(r)})}}</script>

这里是调用 的 topics 列表接口,并且将结果打印出来。

https://img-/0826143745291?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvRnVuZ0xlbw==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast

以上是所有人可以调试的接口 以及写死的接口

以下是个人动态的接口以及代理配置 因为是开发环境需要

至于为什么会需要代理 是因为跨域问题 具体各位百度 个人知识浅薄 可能讲的不好

配置文件 vue.config.js

位置在项目根目录下(因为好多博客并不说明文件位置 像我一样小白会当初傻逼)

const vueConfig = {devServer: {// development server port 8000port: 8085,// If you want to turn on the proxy, please remove the mockjs /src/main.jsL11proxy: {'/apis': {// /apis对接匹配你接口文件的之后动态的路径target: 'http://116.199.15.19:8070/apis',// target: 'http://192.168.3.105:8001',ws: false,changeOrigin: true,pathRewrite: {'^/apis': '/',},},'/files': {target: 'http://116.199.15.19:8070/files',ws: false,changeOrigin: true,pathRewrite: {'^/files': '/',},},},},};module.exports = vueConfig;

到此你接口配置好了 接下来就是对于接口url接上具体的文件名称之类,以及对于验证参数的传参之类的 以下是我的登录验证 src/view/login.vue

handlevalue()方法就是对接口进行补充传参验证做路由跳转

<template><div id="components-layout-demo-basic"><a-layout class="layout-login"><a-layout-header><div><div><img src="@/assets/logo-header.svg" alt="" style="height: 44px; margin-right: 16px; border-style: none" /><span class="header-title">Ant Design</span></div><div class="desc">Ant Design 是西湖区最具影响力的 Web 设计规范</div></div></a-layout-header><a-layout-content class="content-body"><div class="content-header"><a-tabs default-active-key="1" @change="callback"><a-tab-pane key="1" tab="账户密码登录"><a-form id="components-form-demo-normal-login" :form="form" class="login-form" @submit="handleSubmit"><a-form-item style="text-align: left"><a-inputv-decorator="['userName', { rules: [{ required: true, message: '请输入帐户名或邮箱地址' }] }]"class="input-header"placeholder="账户: admin"size="large"><a-icon slot="prefix" type="user" style="color: rgba(0, 0, 0, 0.25)" /></a-input></a-form-item><a-form-item style="text-align: left"><a-input-passwordv-decorator="['password', { rules: [{ required: true, message: '请输入密码!' }] }]"type="password"placeholder="密码: admin or ant.design"size="large"userName><a-icon slot="prefix" type="lock" style="color: rgba(0, 0, 0, 0.25)" /></a-input-password></a-form-item><!-- <a-form-item><a-checkboxv-decorator="['remember',{valuePropName: 'checked',initialValue: true,},]"class="checkbox-left">记住密码</a-checkbox><a class="login-form-forgot" href=""> 自动登录 </a><a-button type="primary" html-type="submit" class="login-form-button"> 登录 </a-button>Or<a href=""> register now! </a></a-form-item> --></a-form></a-tab-pane><a-tab-pane key="2" tab="手机号登录" force-render style="text-align: left"><a-form id="components-form-demo-normal-login" :form="form" class="login-form" @submit="handleSubmit"><a-form-item><a-inputv-decorator="['phone', { rules: [{ required: true, message: '请输入手机号' }] }]"class="input-header"placeholder="手机号"size="large"><a-icon slot="prefix" type="mobile" style="color: rgba(0, 0, 0, 0.25)" /></a-input></a-form-item><a-form-item @submit="handleSubmit"><span><a-inputv-decorator="['verificationCode', { rules: [{ required: true, message: '请输入验证码!' }] }]"type="password"placeholder="验证码"size="large"style="float: left; width: 65%"><a-icon slot="prefix" type="mail" style="color: rgba(0, 0, 0, 0.25)" /></a-input><a-button size="large" style="float: right; font-size: 14px; width: 30%" html-type="submit"> 获取验证码 </a-button></span></a-form-item></a-form></a-tab-pane></a-tabs></div><div class="content-header"><a-form id="components-form-demo-normal-login" class="login-form" @submit="handleSubmit"><a-form-item><a-checkboxv-decorator="['remember',{valuePropName: 'checked',initialValue: true,},]"class="checkbox-left">自动登录</a-checkbox><a class="login-form-forgot" href=""> 忘记密码 </a><a-button size="large" type="primary" class="login-form-button" html-type="submit" @click="handlevalue()">登录</a-button><!-- <router-link :to="{ path: this.routervalue }">登录</router-link> --></a-form-item><div style="text-align: left"><span style="float: left">其他登录方式</span><a-icon class="icon-all" type="alipay" /><a-icon class="icon-all" type="taobao" /><a-iconclass="icon-all"type="weibo"/><a style="float: right" href=""> 注册账户 </a></div></a-form></div></a-layout-content><a-layout-footer class="footer"><div style="padding-left: 40px; margin-bottom: 8px"><span style="padding-right: 40px">帮助</span><span style="padding-right: 40px">隐私</span><span style="padding-right: 40px">条款</span></div><div>Copyright © vueComponent</div></a-layout-footer></a-layout></div></template><script>export default {data() {return {routervalue: '',name: '',password: '',// status: '',// name: this.form.getFieldValue('userName'),// form: [// {//password: '',//userName: '123',//phone: '',//verificationCode: '',// },// ],};},beforeCreate() {this.form = this.$form.createForm(this, {name: 'normal_login' });},mounted() {},methods: {callback(key) {// console.log(key);},handlevalue() {this.name = this.form.getFieldValue('userName');this.password = this.form.getFieldValue('password');this.$api.post('/auth/login', {userName: this.name, password: this.password }, (r) => {const status = '';this.status = r.success;// console.log(this.status);// console.log(this.name);// console.log(this.password);if ((this.status = true)) {this.routervalue = '/home';console.log(this.status);console.log(this.form.getFieldValue('password'));console.log(this.name);this.$router.push(this.routervalue);}});},handleSubmit(e) {e.preventDefault();this.form.validateFields((err, values) => {if (!err) {console.log('Received values of form: ', values);}});},},};</script><style>#components-layout-demo-basic {text-align: center;}#components-layout-demo-basic .ant-layout-header,#components-layout-demo-basic .ant-layout-footer {background: transparent;/* color: red; */}#components-layout-demo-basic .ant-layout-footer {line-height: 1.5;}#components-layout-demo-basic .ant-layout-content {background: transparent;/* color: red; *//* min-height: 120px; */line-height: 120px;}#components-layout-demo-basic > .ant-layout {margin-bottom: 48px;}#components-layout-demo-basic > .ant-layout:last-child {margin: 0;}.layout-login {width: 100%;min-height: 540px;background: #f0f2f5 url(../assets/bg-login.svg) no-repeat 50%;background-size: 100%;position: relative;padding: 54px 0 74px;}.header-title {font-size: 33px;color: rgba(0, 0, 0, 0.85);font-family: Avenir, Helvetica Neue, Arial, Helvetica, sans-serif;font-weight: 600;position: relative;top: 10px;}.desc {font-size: 14px;color: rgba(0, 0, 0, 0.45);line-height: 0px;margin-top: 15px;margin-bottom: 40px;}.content-header {margin-top: 200px;width: 368px;/* height: 350px; */overflow: auto;margin: auto;/* position: absolute;top: 250px;left: 0;right: 0; */}.content-body {margin-top: 70px;}.checkbox-left {float: left;}.input-header {height: 40px;}.icon-all {/* color: rgba(0, 0, 0, 0.2); */color: #f0f2f5;font-size: 18px;background-color: rgb(192, 194, 196);border-radius: 20px;margin-left: 16px;padding: 3px;}.footer {width: 100%;bottom: 0;padding: 0 16px;margin: 48px 0 24px;text-align: center;color: rgba(0, 0, 0, 0.45);}/* 表单 */#components-form-demo-normal-login .login-form {max-width: 300px;}#components-form-demo-normal-login .login-form-forgot {float: right;}#components-form-demo-normal-login .login-form-button {width: 100%;margin-top: 24px;}</style>

参考/fungleo/article/details/77601761

编写总结不易 点赞关注收藏三连一波 哈哈哈

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。