0

我正在尝试将异步函数作为属性从外部应用程序传递给 vuejs 组件,但是我遇到了以下问题。

假设在我的非 vue 组件中我定义了这个函数

var myComponent = {
     myVar: "test",
     myFunc: async function (cookie) {
              console.log(this.myVar); //yields an error in the vue instance but works normally in the component
              return await new Promise((resolve, reject) => {
                //if success
                let success = true;
                if (success) {
                  setTimeout(function() {
                    resolve('Saved after 5000ms: ');
                  }, 5000);
                } else {
                  reject('An error occurred');
                }
              });
            },
    }

在一个系统中,我在另一个 asyncFunc2 中有 asyncFunc1,它们都执行相同的工作,但在各自的环境中采用完全不同的方式,并且两个系统都将初始化相同的 vue 组件,并将它们自己的函数作为道具传递。我无法在其中声明此函数Vue 组件,因为它需要在不同的外部环境中以不同的方式定义。

var component = this;
var vm = new Vue({
            i18n,
            el: '#app',
            render(h) {
              return h(App, {
                props: {
                  myFunc: component.myFunc, //async function
                },
                ref: 'test',
              });
            },
          });

我的 Vue 组件将调用通过 prop 传递的这个函数,然后再使用它的内部方法完成它自己的工作。

所以我现在的问题是,当函数作为道具传递时,this对 Vue 实例的引用会从原始组件更改,因此我无法正确使用我的函数。据说对象和函数是在 props 中通过引用传递的,但这里似乎并非如此。

我该如何克服这个问题?

4

0 回答 0