Tutorial

Use Web Workers with Ease in Vue.js with vue-worker

Vue.js

While this tutorial has content that we believe is of great benefit to our community, we have not yet tested or edited it to ensure you have an error-free learning experience. It's on our list, and we're working on it! You can help us out by using the "report an issue" button at the bottom of the tutorial.

Like many developers, when Web Workers first emerged onto the web development scene, I was incredibly enthusiastic and dreampt of the various amazing things I could accomplish with them. However, my enthusiasm was quickly dampened when I realized that workers had to be loaded from separate files hosted on the webserver. That seemed like a huge pain that wasn’t worth the effort. Combined with the API overhead, I haven’t really used workers again since my first try until now. Looking at vue-worker, I’m suddenly amazed again at what can be accomplished in my Vue.js apps with a nice simple API and no external files.

The core premise of vue-worker (or rather, simple-web-worker by the same author) is that Web Workers can be initialized from a Data URI, which can just be a stringified function.

vue-worker wraps the complexity involved in that with a simple, easy-to-understand API, allowing you to easily execute multitheaded functions just like promises.

Installation

Install vue-worker via Yarn or NPM:

# Yarn
$ yarn add vue-worker

# NPM
$ npm install vue-worker --save

Now, enable the VueWorker plugin:

src/main.js
import Vue from 'vue';
import VueWorker from 'vue-worker';
import App from 'App.vue';

Vue.use(VueWorker);

new Vue({
  el: '#app',
  render: h => h(App)
});

This provides your components with the ability to access this.$worker.

Running Functions in the Worker

Now, inside your component you can use this.$worker.run(function, args[]).

This runs a function that outputs Hello, World! in a worker thread when the component is mounted:

<script>
export default {
  mounted() {
    this.$worker.run((arg) => {
      return `Hello, ${arg}!`
    }, ['World'])
    .then(result => {
      console.log(result)
    })
    .catch(e => {
      console.error(e)
    })
  }
}
</script>

Reusable Workers

You can create a reuseable *“worker”* proxy with this.$worker.create([{message, func}]).

<script>
export default {
  data() {
    return {
      myWorker: null
    }
  },

  created() {
    this.myWorker = this.$worker.create([
      {message: 'message1', func: (arg) => `Output 1 ${arg}`},
      {message: 'message2', func: () => 'Output 2'}
    ])

    this.myWorker.postMessage('message1', ['Boop!'])
    .then(result => {
      console.log(result)
    })
  }
}
</script>

There’s plenty more you can do too, take a look at the vue-worker and simple-worker docs.

Creative Commons License