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.
Install vue-worker via Yarn or NPM:
# Yarn
$ yarn add vue-worker
# NPM
$ npm install vue-worker --save
Now, enable the VueWorker plugin:
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
.
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>
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.
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.
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!