如何调用返回值是异步请求函数的函数

在vue的methods,函数search作用是返回请求数据,但是报错

search(options) {
  const url = this.isTeacher? '/api/search_Teacher' : '/apis/org/search_student';
  const params = options.ids ? { ids: options.ids } : { keyword: this.keyword };
 return this.$http.get(url, { params }).then((response) => {
   return response.body;
  }, (err) =>{
   console.log(err);
  })
},

但是不明白如何调用这个search,获取到data??
尝试下面的方法,报错,this.search is not a function??

  this.seach({ ids: this.selected }).then((res) => {
    if (!res) this.$message.error('搜索失败');
    else this.selectedData = res;
  });

有没有好的方法,谢谢

阅读 3.4k
3 个回答
async search(options) {
  const url = this.isTeacher? '/api/search_Teacher' : '/apis/org/search_student';
  const params = options.ids ? { ids: options.ids } : { keyword: this.keyword };
  try {
    const res = await this.$http.get(url, { params })
    return res.body
  } catch (e) {
    console.log(e)
  }
},

use

const data = await this.search({ ids: this.selected })
if (!data) this.$message.error('搜索失败');
else this.selectedData = data;
search(options) {
  const url = this.isTeacher? '/api/search_Teacher' : '/apis/org/search_student';
  const params = options.ids ? { ids: options.ids } : { keyword: this.keyword };
  this.$http.get(url, { params }).then((response) => {
  this.xxx = response.body;
   console.log(this.xxx);
  },(err) =>{
   console.log(err);
  })
},

你调用写的是 seach 不是 search

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题