是否可以在 .vue 组件中访问 Web Worker

Is it possible to access Web Workers inside a .vue component

所以我正在考虑创建这个应用程序,它使用我发现的生成魔方块打乱的网络工作人员(实际上,生成随机状态打乱是一个密集的过程,特别是对于更大的立方体,所以网络工作人员对于这种情况是必需的)。我想知道是否可以从 vue 组件内部访问这个网络工作者(服务工作者文件或访问它会不会有任何问题。如果可能,我将如何让它工作?

是的,你可以,这是一个演示:

Vue.component('my-component', {
  template: '#my-component',
  data() {
    return {
      cube: '-- no data yet --',
      worker: null
    };
  },
  created() {
    this.initWorker();
  },
  beforeDestroy() {
    this.destroyWorker();
  },
  methods: {
    initWorker() {
      // Here, just for this demo to work, I'm not using an external file
      // for the worker. Instead, I use a Blob. It's still a real Worker!
      // See 
      const scriptBlob = new Blob(
        [ document.querySelector('#worker-script').textContent ],
        { type: "text/javascript" }
      );
      this.worker = new Worker(window.URL.createObjectURL(scriptBlob));
      this.worker.onmessage = e => this.onCubeReady(e.data);
    },
    destroyWorker() {
      this.worker.terminate();
    },
    scrambleCube() {
      this.cube = '-- Scrambling cube... --'
      this.worker.postMessage('Gimme a cube');
    },
    onCubeReady(cube) {
      this.cube = cube;
    }
  }
});

var vm = new Vue({
  el: '#app'
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.21/vue.min.js"></script>

<div id="app">
  <my-component></my-component>
</div>

<template id="my-component">
  <div>
    <button @click="scrambleCube">Scramble cube</button>
    <pre>{{cube}}</pre>
  </div>
</template>

<!-- This is just for the demo, and won't be parsed
     because of type="javascript/worker".
     we load it into a Blob to make it a worker -->
<script type="javascript/worker" id="worker-script">
self.addEventListener("message", onMessageReceive);

function onMessageReceive(e) {
  console.log(`Worker received a message`);
  const res = heavyProcessing();
  self.postMessage(res);
}

function heavyProcessing() {
  const endTime = Date.now() + 2000;
  while (Date.now() < endTime) {}
  return 'CUBE MADE BY A WORKER';
}
</script>