【前端】多线程 worker
VUE3 引用
npm install worker-loader
在vue.config.js文件
的defineConfig里加上配置参数
chainWebpack: config => {
config.module
.rule('worker-loader')
.test(/\.worker\.js$/)
.use({
loader: 'worker-loader',
options: {
inline: true
}
})
.loader('worker-loader')
.end()
}
先在src目录
下新建workers文件夹
,接着在里面新建worker.js
,在js文件里添加下面的测试代码:
addEventListener('message', e => {
const { data } = e
console.log(data)
setTimeout(() => {
return postMessage('线程完成')
}, 1000)
})
export default {}
测试
<template>
<div>
<h1>vue3-Worker</h1>
<button @click="openWorker">开启线程</button>
<p>F12打开浏览器控制台查看效果</p>
</div>
</template>
<script setup>
import Worker from 'worker-loader!@/workers/worker'
const openWorker = () => {
const worker = new Worker()
worker.postMessage('开启线程')
worker.onmessage = e => {
console.log(e.data)
setTimeout(() => {
worker.postMessage('线程关闭')
worker.terminate()
}, 1000)
}
}
</script>