vue-worker的使用
1.介紹:改插件將復雜的worker進行了一次的封裝,暴露出幾個方法簡單好用
// 安裝插件 npm install vue-worker --save // 在main.js引入使用 import VueWorker from 'vue-worker' Vue.use(VueWorker) // 在組件中使用,直接this.$worker就可以使用 /* API:run()方法的使用,第一個參數是一個函數,用於處理數據,第二個參數是一個數組,是函數的實參。run方法執行一次就會斷開,支持promise */ this.$worker.run((n, b) => n + 10 + b, [2, 10]).then(res => { console.log(res) }) /* API:create()方法,可以持久化worker,接收一個數組參數,數組中是每一個對象,對象中是id和方法 */ worker: null, action: [{ message: 'abc', func (data) { return data } }, { message: 'msg', func (data) { return data } }] this.worker = this.$worker.create(this.action) // postMessage實例對象方法,第一個參數是要觸發那個對象中的方法,第二個參數是傳遞給方法中的實參 this.worker.postMessage('msg', [{ name: '哈哈哈' }]).then(res => { console.log(res) }) /* API:postAll實例方法,如果不傳遞參數,會觸發所有對象中的方法,參數可以是字符串,或者對象和數組 */ // 數組參數:數組中必須是對象,message屬性標示觸發那個方法,第二個屬性args是給方法傳遞的實參 this.worker.postAll([{ message: 'pull-data', args: [{ name: '小蘭' }] }]) .then((res1, res2) => { console.log(res1) }) // 字符串形式 this.worker.postAll('pull-data') .then((res1, res2) => { console.log(res1) }) /* API;register實例方法,可以動態注冊方法和標示 */ this.worker.register({ message: 'copu', func: () => 1 }) // unregister方法可以取消注冊 this.worker.unregister('copu') this.worker.unregister('pull-data')