【问题标题】:Is it possible to access Web Workers inside a .vue component是否可以在 .vue 组件中访问 Web Worker
【发布时间】:2020-10-10 22:15:10
【问题描述】:

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

【问题讨论】:

    标签: javascript vue.js web-applications frontend web-worker


    【解决方案1】:

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

    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 https://stackoverflow.com/a/6454685/1913729
          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>

    【讨论】:

    • 我已经开始着手处理这件事,只是将一个调用 web worker 的函数放在另一个文件中以使其更干净,但感谢您的帮助。到目前为止一切正常。
    • 我实际上做了一个 speedcubing 计时器,它使用 indexeddb 来存储每种类型的谜题的时间不是你会关心的,因为你不是一个立方体,而是 here 这是一个全栈站点的概念我打算尽快做。
    猜你喜欢
    • 2022-10-19
    • 2021-08-26
    • 2017-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-28
    • 2020-03-08
    • 1970-01-01
    相关资源
    最近更新 更多