在vue组件中使用Worker输出



我试图通过window.localStorage.将工作人员的输出发送到我的组件.vue

有人知道如何在我的组件vue中自动显示和更新我的工作人员的结果吗?

这是我的代码:

worker-api.js

import Worker from "worker-loader!./worker.js";
const worker = new Worker();
worker.addEventListener('message', (e) => {
window.localStorage.setItem('result', JSON.stringify(e.data));
});
export function sendMessage(msg) {
worker.postMessage(msg);
}

worker.js

self.addEventListener("message", (e) => {
var count = e.data;
while(count < 20) {        
const result = e.data + 3 
self.postMessage(result);
} 
});

我的组件.vue

<template>
<p>Count: "{{ result }}"</p>
</template>
<script>
import Button from './Button'
import { sendMessage } from './worker-api'
export default {
name: 'my-component',
components: {Button},
data () {
return {
count : 0
}
},
computed: {
result: function () {
return JSON.parse(window.localStorage.getItem('result'))
}
},
methods: {,
postMessage() {
sendMessage(this.count)
}
},
}
</script>

不可能将localStorage值当作被动值来处理。也许,这就是你的计算属性不起作用的原因。

一种可能的解决方案是将您的工作人员导入组件中,并用于更新反应变量。

类似于:

component.vue

<template>
<button @click="increment">Increment Result</button>
{{ result }}
</template>
<script>
export default {
data() {
return {
// the worker path must be relative to the /public folder (in this example, the worker.js file must be at /public/worker.js)
worker: new Worker('/worker.js'),
result: 0
}
},
created() {
const self = this
this.worker.onmessage = function(event) {
self.result = event.data
}
},
methods: {
increment() {
this.worker.postMessage(this.result)
}
}
}
</script>

/public/worker.js

onmessage = function(event) {
// data sent by the Vue component is retrieved from 'data' attribute
postMessage(event.data + 1)
}

相关内容

  • 没有找到相关文章

最新更新