vue 使用axios

目前主流的 Vue 项目,都选择 axios 来完成 ajax 请求,而大型项目都会使用 Vuex 来管理数据。

前言: 

使用 cnpm 安装 axios

cnpm install axios -S

安装其他插件的时候,可以直接在 main.js 中引入并 Vue.use(),但是 axios 并不能 use,只能每个需要发送请求的组件中即时引入

为了解决这个问题,是在引入 axios 之后,修改原型链具体的实施请往下看~

改写原型链

首先在 main.js 中引入 axios

import axios from 'axios'

这时候如果在其它的组件中,是无法使用 axios 命令的。但如果将 axios 改写为 Vue 的原型属性,就能解决这个问题

Vue.prototype.$ajax = axios

在 main.js 中添加了这两行代码之后,就能直接在组件的 methods 中使用 $ajax 命令

复制代码
methods: {
  but_ajax() {
    this.$ajax({
      method: 'post',
      url: 'http://192.168.0.113:8080/llhb/m/requirement/allCategor',
      params: {                    //需要发送的数据
        name: 'zhangwenwu2',
        age: '15'
      }
   })
   //请求成功后执行then          如果直接在里面访问 this,无法访问到 Vue 实例,this指向发生了变化。建议使用箭头函数,下面有讲
   .then(function (response) {
        console.log(response);   //处理后台返回的数据
     }) 
 
 
   //请求失败后执行catch
 
 
   .catch(function(err){
        console.log(err)
     })
}
复制代码

附录:配置 axios 

上面封装的方法中,使用了 axios 的三个配置项,实际上只有 url 是必须的,完整的 api 可以参考使用说明

为了方便,axios 还为每种方法起了别名,比如上面的 saveForm 方法等价于:

axios.post('/user', context.state.test02)

完整的请求还应当包括 .then 和 .catch

.then(function(res){
  console.log(res)
})
.catch(function(err){
  console.log(err)
})

当请求成功时,会执行 .then,否则执行 .catch

这两个回调函数都有各自独立的作用域,如果直接在里面访问 this,无法访问到 Vue 实例,this指向发生了变化。

这时只要添加一个 .bind(this) 就能解决这个问题,或者使用箭头函数即可

.then(function(res){
  console.log(this.data)
}.bind(this))
.then((res) => {
  console.log(this.data)
})

猜你喜欢

转载自www.cnblogs.com/zhaohuanhuan/p/9254490.html