调用辅助函数时出现问题 - Vue

Problem when calling the helper function - Vue

主视图:

<script>
import { testMethod1 } from "../helper";
export default {
  methods: {
    init(){
      console.log("Res:",  testMethod1());
    }
  }
}
</script>

助手:

import DataService from "../services/data.service";
export  function testMethod1() {
    DataService.getByPage()
        .then((response) => {
            console.log(response)
          return response;
        })
      .catch((error) => {
        console.log(error);
     })
}

输出:

视角:

Res: undefined

来自助手:

0: {_id: "60b621b4809e4304e04e7df4", desc: "aaa", …} 1: {_id: "60b621b4809e4304e04e7df5", desc: "bbb", …} (..)

我做错了什么?

从 helper 导入方法后,您还需要在方法部分声明它,如:

<script>
import { testMethod1 } from "../helper";
export default {
  methods: {
    testMethod1, // this is same with testMethod1: testMethod1,
    init(){
      console.log("Res:",  this.testMethod1());
    }
  }
}
</script>

// See this is the same error

const incorrectFoo = () => {
  fetch('https://jsonplaceholder.typicode.com/todos/1')
  .then(response => response.json())
  .then(json => json)
}



const correctFoo = () => {
 return fetch('https://jsonplaceholder.typicode.com/todos/1')
  .then(response => response.json())
  .then(json => json)
}

const someOtherFoo = async () => {
 console.log('incorrect foo', await incorrectFoo(), 'correctFoo', await correctFoo())

}

someOtherFoo()

此方法正在执行异步调用,

export  function testMethod1() {
    DataService.getByPage()
        .then((response) => {
            console.log(response)
          return response;
        })
      .catch((error) => {
        console.log(error);
     })
}

现在,如果您注意到 DatasService 是一个异步调用,并且该异步调用会进入另一个上下文,每当它被解析时 returns response 这意味着 testMethod1 不是以任何方式返回任何东西试试这个

export  function testMethod1() {
    return DataService.getByPage()
        .then((response) => {
            console.log(response)
          return response;
        })
      .catch((error) => {
        console.log(error);
     })
}

<script>
import { testMethod1 } from "../helper";
export default {
  methods: {
    async init(){
      console.log("Res:",  await testMethod1());
    }
  }
}
</script>