A-Frame 组件不适用于 ES6 模块?

A-Frame component doesn't work with ES6 Modules?

我想在我的 AFRAME 组件的初始化函数中调用另一个 javascript 文件 (a.js) 中的函数 (foo)。

在我的 index.html 中是这样的:

<script type="module">
    import {foo} from "a.js";
    AFRAME.registerComponent('registerevents', {
     init: function () {
         foo();
     }
    }
}

当我这样做时,甚至没有调用 init 函数。

然后我尝试了这样的事情:

<script type="module" src="a.js"></script>
<script>
    AFRAME.registerComponent('registerevents', {
     init: function () {
         foo();
     }
    }
}

在这种情况下我得到了一个未定义的函数。

然后我尝试了 a.js

window.foo = foo;

在我的 index.html:

<script type="module" src="a.js"></script>
<script>
    AFRAME.registerComponent('registerevents', {
     init: function () {
         window.foo();
     }
    }
}

然后我得到一个 window.foo is not a function 错误。 在 init 函数中调用函数的正确方法应该是什么? 谢谢!

模块和 A 型框架工作正常。问题是 init 方法在实体上设置组件之前不会被调用。例如,您可以按如下方式在 a-scene 上设置它:

<script type="module">
    import {foo} from './a.mjs';
    AFRAME.registerComponent('registerevents', {
     init: function () {
         foo();
     }
    }); 
    AFRAME.scenes[0].setAttribute('registerevents','');                         
</script>

其中 a.mjs 是:


export function foo(){ console.log('Fooing is believing!')}

工作示例:https://glitch.com/edit/#!/little-coral

你可以这样做:

const AFRAME = window.AFRAME;

const Initialize = () => {
  AFRAME.registerComponent("a-scene", {
    schema: {
      background: { type: "color", default: "#000" },
    },
  });
};

然后使用效果:

useEffect(()=>{
   Initialize()
})