【问题标题】:Problem when calling the helper function - Vue调用辅助函数时出现问题 - Vue
【发布时间】:2021-08-22 08:50:45
【问题描述】:

主视图:

<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: 未定义

来自助手:

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

我做错了什么?

【问题讨论】:

标签: javascript function vue.js helper


【解决方案1】:

// 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 是一个异步调用,并且该异步调用会到达另一个上下文,只要解决它就会返回 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>

【讨论】:

  • 异步没有帮助,仍然返回 undefined
  • 你在DataService之前添加了return
  • 我没注意到,现在可以了,谢谢:)
【解决方案2】:

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

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

【讨论】:

  • 是的,因为我刚刚看到我们忘了添加这个。在调用方法之前。再次检查我的答案
  • 这行不通,问题testMethod1 总是被识别,因此不需要将其添加到 vue 实例中。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多