Tutorial

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

Published on May 16, 2017
Default avatar

By Joshua Bemenderfer

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

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking 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.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about us


About the authors
Default avatar
Joshua Bemenderfer

author

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
Leave a comment


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Get our biweekly newsletter

Sign up for Infrastructure as a Newsletter.

Hollie's Hub for Good

Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

Become a contributor

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

Welcome to the developer cloud

DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

Learn more
DigitalOcean Cloud Control Panel