在Vue中需要使用例外的线程去执行轮询的任务,这里以获取网卡信息为例。
注:这里是在Electron中使用的,可以使用Node.js实例 “child_process”,如果是纯Vue工程无法使用Node实例。
1.创建一个renderer.js文件,放在public静态文件夹下。
这里以获取网卡信息为例:
// This file is required by the index.html file and will
// be executed in the renderer process for that window.
// No Node.js APIs are available in this process because
// `nodeIntegration` is turned off. Use `preload.js` to
// selectively enable features needed in the rendering
// process.
var cluster = require('child_process')
setInterval(() => {
cluster.exec("cmd /c chcp 65001>nul && netsh wlan show interface", (err, res) => {
var node_nics = require("os").networkInterfaces();
var lines = res.split('\r\n');
var fields = [
'name',
'model',
'vendor',
'mac_address',
'status',
'ssid',
'bssid',
'mode',
'radio',
'authentication',
'encryption',
'connection',
'channel',
'reception',
'transmission',
'signal',
'profil'
];
var connections = [];
var tmp = {}
var len = 0;
for (var i = 3; i < lines.length; i++) {
if (lines[i] != "" && lines[i] != null && lines[i].indexOf(":") != -1) {
tmp[fields[len]] = lines[i].split(':')[1].trim()
len += 1;
} else {
if (tmp['name'] != null && tmp['model'] != null && tmp['vendor'] != null && tmp['mac_address'] != null && tmp['status'] != null) {
var node_nic = node_nics[tmp.name] || [];
node_nic.forEach(function (type) {
if (type.family == 'IPv4') {
tmp.ip_address = type.address;
tmp.ip_gateway = "http://"+type.address.split('.')[0] + "." + type.address.split('.')[1] + "." + type.address.split('.')[2] + ".1"
}
});
connections.push(tmp);
tmp = {}
len = 0;
}
}
}
console.log(connections)
self.postMessage(connections);
})
}, 2000)
2.home.vue
var worker = new Worker("/renderer.js");
export default {
name: "home",
data() {
return {
lists: ""
}
},
created(){
var that = this;
worker.onmessage = function(event) {
this.lists = event.data;
}
},
}