我正在使用Vuetify表单验证来检查输入字段,我想知道是否可以调用ajax get调用并让它等待,这样我就可以在规则中使用结果了。
我已经在下面尝试过了,但似乎不起作用!
export default {
data() {
return {
rules: {
isLocationNew: value => {
if (value == '' || value == null || value.length <= 1) {
this.validLocation = false;
return 'Invalid length.';
}
this.validLocation = true;
var hasName = this.newLocationNameSearch(value);
if (hasName) {
return 'Location name already exists.';
} else {
return true;
}
}
},
// down in methods
methods: {
async newLocationNameSearch(text) {
if (text == '' || text == null || text.length <= 1) {
return false;
}
await axios.get('/api/Locations/HasLocationName', {
params: {
text: text,
jobsiteId: this.jobsiteId
}
}).then(response => {
return response.data;
}).catch(function(error) {
console.log(error)
})
}
}
发布于 2019-05-29 06:24:20
newLocationNameSearch
是一个异步函数。异步函数返回promises,因此当您编写
var hasName = this.newLocationNameSearch(value);
hasName被设置为一个承诺,它总是真实的。
你需要这样的东西:
isLocationNew: async value => {
if (value == '' || value == null || value.length <= 1) {
this.validLocation = false;
return 'Invalid length.';
}
this.validLocation = true;
var hasName = await this.newLocationNameSearch(value);
if (hasName) {
return 'Location name already exists.';
} else {
return true;
}
}
请记住,无论在哪里调用isLocationNew,都需要等待它。
此外,newLocationNameSearch
方法在等待时实际上并不返回值。
await axios.get('/api/Locations/HasLocationName', {
params: {
text: text,
jobsiteId: this.jobsiteId
}
}).then(response => {
return response.data;
}).catch(function(error) {
console.log(error)
})
在.then()
调用的回调中包含返回语句。然后,newLocationNameSearch
不返回任何内容,这意味着它返回undefined
,这是错误的。
好消息是,async/await意味着我们不必再为then
回调而烦恼了。
我们可以改写
try {
var response = await axios.get('/api/Locations/HasLocationName', {
params: {
text: text,
jobsiteId: this.jobsiteId
}
});
return response.data;
} catch (error) {
console.log(error)
}
发布于 2019-05-29 07:10:27
methods: {
fetchUserData: async function() {
const response = await fetch(
"https://jsonplaceholder.typicode.com/users"
);
this.users = await response.json();
}
你可以像这个例子一样使用它。
https://stackoverflow.com/questions/56350690
复制相似问题