在使用axios发送请求时,this指向的问题是常见的问题,这通常涉及到在组件中使用axios时,使用箭头函数绑定this的值,从而避免出现问题。
首先,需要明确一点,axios中的this指向与组件的this指向是不同的。axios中的this指向axios实例本身,而不是组件实例。因此,在组件中直接使用this是无法访问到axios实例的。
如果在组件中需要使用axios,常见的做法是将axios实例作为组件实例的一个属性,并在需要发送请求的方法中使用该属性。例如,在组件的mounted生命周期中创建axios实例,并将其赋给组件的$http属性:
mounted() {
this.$http = axios.create({
baseURL: 'https://jsonplaceholder.typicode.com/',
timeout: 1000,
});
}
然后,在需要发送请求的方法中,使用组件实例的$http属性来发送请求,例如:
methods: {
fetchData() {
this.$http.get('posts')
.then((response) => {
// do something
})
.catch((error) => {
// handle error
});
},
},
需要注意的是,在组件中使用$http属性是需要绑定this的,否则this指向的是window对象,而不是当前组件实例。可以使用箭头函数或bind()方法来绑定this的值,例如:
methods: {
fetchData() {
this.$http.get('posts')
.then((response) => {
this.posts = response.data;
})
.catch(function (error) {
console.log(error);
}.bind(this));
},
},
或者:
methods: {
fetchData: function () {
this.$http.get('posts')
.then(function (response) {
this.posts = response.data;
}.bind(this))
.catch(function (error) {
console.log(error);
}.bind(this));
},
},