0.2.0 • Published 4 years ago
vue-web-workers v0.2.0
vue-web-workers
A Vue component to use Web Workers in a simply way
Install
yarn add vue-web-workers
npm install vue-web-workers
Use
export interface WorkerSync extends Worker {
// use postMessage as Promise
postMessageSync?: (message: any, options?: any) => Promise<any>;
}
...
import VueWebWorkers, { WorkerSync } from "vue-web-workers";
@Component({
components: { VueWebWorkers }
})
export default DEMO extends Vue {
private worker: WorkerSync | null = null;
private postMessage = { action: "", data: null };
public onMessage(args: any) {
console.log(args);
}
public sendByWorker() {
if (this.worker) {
if (this.worker.postMessageSync) {
// 当 syncKey 的值等于 postMessage 对象的标识,比如 action
// 这个时候就可以使用 postMessage 的 异步结构 postMessageSync
this.worker
.postMessageSync({ action: "sendByWorker", data: null })
.then(res => console.log(res));
}else{
this.worker.postMessage({ action: "sendByWorker", data: null });
}
}
}
public sendByPostMessage() {
this.postMessage = {
action: "sendByPostMessage",
data: null
};
}
protected render() {
return (
<div >
<VueWebWorkers v-model="worker" syncKey="action" @message="onMessage" :postMessage="postMessage">
addEventListener('message', async (event) => {
setTimeout(() => postMessage(Object.assign({}, event.data, {state: true})), 1000)
})
</VueWebWorkers>
<button @click="sendByWorker">SendByWorker</button>
<button @click="sendByPostMessage">SendByPostMessage</button>
</div>
)
}
}
Customize configuration
See GitHub.