【发布时间】:2017-11-20 18:46:00
【问题描述】:
我正在执行异步验证,我需要在 vuejs 中全局访问 $axios 集,但这失败了
Validator.extend('async_validate_job_type', {
getMessage: field => `The Name already exists`,
validate: value => new Promise((resolve) => {
//validate email.
this.$axios.post('/validate/position-type', {email:value})
.then(
....perform stuff here
)
})
});
现在上面抛出一个错误
cannot read propery post of undefined
在其他组件中使用this.$axios.post 有效。但在上面似乎我无法访问 this.$axios。我哪里错了?
我已经通过 axios 设置了
Vue.prototype.$axios = axios.create(axiosConfig);
同样使用像这样的正常功能也会失败
Validator.extend('async_validate_job_type', {
getMessage: field => `The Name already exists`,
validate(value){
return new Promise((resolve) => {
console.log("value of this is", this); //this is undefined
this.$axios.post())
})
}
});
【问题讨论】:
-
我只是将 axios 发送到
window,而不是添加到 Vue 原型中。但是,我猜你有一个范围问题,this实际上是指窗口而不是 Vue 实例。尝试使用普通函数:validate(value) { return new Promise(...)} -
在普通函数中调用 this 也会失败
-
@craig_h ive 用非正常函数尝试更新了同样失败的问题
标签: javascript vue.js vuejs2 axios