vue axios网络请求

https://cli.vuejs.org/ vue-cli 3.0

免费开放接口API

方法一

安装 npm install axios
引入 import axios from 'axios'
Vue.prototype.$http = axios
new Vue ({... ,axios})

post 请求

this.$http.post('接口',{数据})
.then(res => {
})

get 请求

this.$http.get('接口')
.then(res => {
})


// GET 参数可以放到params里(推荐)
this.$http.get('接口', {
    params: {
      ID: 12345
    }
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

方法二 (是对第一种的封装,只是多加了3种写法)

npm install axios vue-axios
import axios from 'axios'
import VueAxios from 'vue-axios'
Vue.use(VueAxios,axios)

get 请求

Vue.axios.get(`/api/article/detail?id=${this.$route.params.id}`)
    .then(res => {
            this.articleDetail = res.data[0];       
     })
    .catch(err => console.log(err))
}

this.axios.get(api).then((response) => {
  console.log(response.data)
})

this.$http.get(api).then((response) => {
  console.log(response.data)
})

post 请求

this.axios.post('接口',{数据})
.then(res => {
})

注意:

链式调用 会导致this为undefined

vue例子

let that = this;//promise 之外
...//中间的其他逻辑          
.then() //链式调用
.then(func(that){...}); //调用其他方法


//其他方法
func(that){
that.xxx   //vue的各类操作。
that.xxx
}

js例子

$(‘#conten').click(function(){
    //this是被点击的#conten
    var that = this;
    $(‘.conten').each(function(){
    //this是.conten循环中当前的对象
    //that仍然是刚才被点击的#conten
    });
});
解决方法:
  • let that = this 用that去处理
.then(res => {
            this.name= res.data;       
     })
//箭头函数 (=>)内部的this是词法作用域,
//是由外层调用者vue来确定,使用箭头函数之后,
//箭头函数指向的函数内部的this已经绑定了外部的vue实例了

闭包





闭包




0

最后总结一下闭包的好处与坏处

好处

①保护函数内的变量安全 ,实现封装,防止变量流入其他环境发生命名冲突

②在内存中维持一个变量,可以做缓存(但使用多了同时也是一项缺点,消耗内存)

③匿名自执行函数可以减少内存消耗

坏处

①其中一点上面已经有体现了,就是被引用的私有变量不能被销毁,增大了内存消耗,造成内存泄漏,解决方法是可以在使用完变量后手动为它赋值为null;

②其次由于闭包涉及跨域访问,所以会导致性能损失,我们可以通过把跨作用域变量存储在局部变量中,然后直接访问局部变量,来减轻对执行速度的影响

你可能感兴趣的:(vue axios网络请求)