异步查询工具axios的简单应用

1 什么是axios

axios是基于Vue的ajax的请求框架,基于promise的HTTP库。

axios语法:

axios.get(url,{}).then(成功).catch(失败)
axios.post(url,{}).then(成功).catch(失败)

官方文档:
在这里插入图片描述

2 axios全局配置

注:axios的使用需基于Vue环境

Xxx.js

import Vue from 'vue'//从vue中引入Vue
Vue.use(Axios)//使用Axios
// 引用axios,并设置基础URL为后端服务api地址
Axios.defaults.baseURL = 'http://127.0.0.1:9527/services'  //对应后端网关统一地址
// 将API方法绑定到全局  /plat/login
Vue.prototype.$http = Axios
Vue.config.productionTip = false

3 Axios的应用

登录验证参考代码

Main.js

import babelpolyfill from 'babel-polyfill'
import Vue from 'vue'
import Axios from 'axios/dist/axios'
import App from './App'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-default/index.css'
//import './assets/theme/theme-green/index.css'
import VueRouter from 'vue-router'
import store from './vuex/store'
import Vuex from 'vuex'
//import NProgress from 'nprogress'
//import 'nprogress/nprogress.css'
import routes from './routes'
// import Mock from './mock'
// Mock.bootstrap();
import 'font-awesome/css/font-awesome.min.css'

Vue.use(ElementUI)
Vue.use(VueRouter)
Vue.use(Vuex)

Vue.use(Axios)
//网关地址
Axios.defaults.baseURL = 'http://localhost:9527/crazytrend'
Vue.prototype.$http = Axios
Vue.config.productionTip = false

const router = new VueRouter({
  routes
})

router.beforeEach((to, from, next) => {
  //NProgress.start();
  if (to.path == '/login') {
    sessionStorage.removeItem('user');
  }
  let user = JSON.parse(sessionStorage.getItem('user'));
  if (!user && to.path != '/login') {
    next({ path: '/login' })
  } else {
    next()
  }
})

//router.afterEach(transition => {
//NProgress.done();
//});

new Vue({
  //el: '#app',
  //template: '<App/>',
  router,
  store,
  //components: { App }
  render: h => h(App)
}).$mount('#app')


Login.vue

<script>
    import {requestLogin} from '../api/api';
    //import NProgress from 'nprogress'
    export default {
        data() {
            return {
                logining: false,
                ruleForm2: {
                    account: 'admin',
                    checkPass: '123456'
                },
                rules2: {
                    account: [
                        {required: true, message: '请输入账号', trigger: 'blur'},
                        //{ validator: validaePass }
                    ],
                    checkPass: [
                        {required: true, message: '请输入密码', trigger: 'blur'},
                        //{ validator: validaePass2 }
                    ]
                },
                checked: true
            };
        },
        methods: {
            handleReset2() {
                this.$refs.ruleForm2.resetFields();
            },
            handleSubmit2(ev) {
                var _this = this;
                this.$refs.ruleForm2.validate((valid) => {
                    if (valid) {
                        //_this.$router.replace('/table');
                        this.logining = true;
                        //NProgress.start();
                        var loginParams = {name: this.ruleForm2.account, pwd: this.ruleForm2.checkPass};
                        //使用axios发送请求
                        /* this.$http.get("/147258").then(data =>{
                             console.debug("iiiiiii")
                             console.debug(data)
                         });*/
                        this.$http.post("/user/user/login").then(d => {

                            this.logining = false;
                            //NProgress.done();
                            console.debug("===============");

                            var data = d.data.data;
                            console.debug(data);
                            let {msg, success, object} = data;
                            if (!success) {
                                this.$message({
                                    message: msg,
                                    type: 'error'
                                });
                            } else {
                                //session放入用户中
                                object = {"name":"kobe"};
                                sessionStorage.setItem('user', JSON.stringify(object));
                                this.$router.push({path: '/table'});
                            }
                        });
                        /* requestLogin(loginParams).then(data => {
                           this.logining = false;
                           //NProgress.done();
                           let { msg, code, user } = data;
                           if (code !== 200) {
                             this.$message({
                               message: msg,
                               type: 'error'
                             });
                           } else {
                             sessionStorage.setItem('user', JSON.stringify(user));
                             this.$router.push({ path: '/table' });
                           }
                         });*/
                    } else {
                        console.log('error submit!!');
                        return false;
                    }
                });
            }
        }
    }

</script>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值