【VUE】4.配置axios发起请求

1.配置axios

  1. 前端请求后端接口进行数据交互的时候,需要配置axios

  2. 导入axios包, main.js

import axios from 'axios'

  3. 挂载到原型配置上,便于所有的组件都可以访问this.$http

// 挂载全局对象
Vue.prototype.$http = axios

  4. 设置axios 请求的根路径

// 配置后端api接口路径
axios.defaults.baseURL = 'http://127.0.0.1:5000/v1'

  

2. 通过axios访问登陆接口

  1. components -> Form.vue , 对预验证进行校验,如果验证不正确就跳出,如果正确,就通过axios请求token接口,并且传入用户名密码

// 预验证
    validForm() {
      this.$refs.FormRef.validate(valid => {
        if (!valid) return
        const res = this.$http.post("token", this.Form)
        console.log(res)
      });
    }

  2. 结果验证

 

   3. 结果是promise , promise,通过async await(只用户async异步函数) 简化promise操作

// 预验证
    validForm() {
      this.$refs.FormRef.validate(async valid => {
        if (!valid) return
        const {data:res} = await this.$http.post("token", this.Form)
        console.log(res)
      });
    }
  }

  

posted @ 2020-05-22 10:00  WANG-X  阅读(432)  评论(0编辑  收藏  举报