如题,我使用了Electron的截图方法,在data()函数中定义了一个picPath用来保存截图的目标路径(通过_self.picPath访问)。截图成功后我用picPath存放forEach函数中的截图路径(只有一个所以直接用了字符串存放)。但是比较神奇的是离开sources.forEach函数后,_self.picPath也变成空的字符串了。
在网上查找资料得知,JS中String属于基本数据类型,互相赋值时为值传递,那为什么还会产生上述情况?
mounted() {
require('electron').ipcRenderer.on('synchronous-reply', (event, message) => {
if (message.content === 'capture') {
const electron = require('electron')
const desktopCapturer = electron.desktopCapturer
const fs = require('fs')
const path = require('path')
var options = { types: ['screen'], thumbnailSize: message.param }
desktopCapturer.getSources(options, function (error, sources) {
if (error) {
console.log(error)
}
sources.forEach(function (source) {
var fileName = (new Date()).valueOf() + '.png'
const screenshotPath = path.join(_self.form.dir, 'Game', 'Screenshots', fileName)
fs.writeFile(screenshotPath, source.thumbnail.toPNG(), function (error) {
if (error) {
console.log(error)
}
})
_self.picPath = screenshotPath
console.log(_self.picPath) // 打印正常路径
})
})
console.log(_self.picPath) // 打印 ''
}
})
}
desktopCapturer.getSources
返回Promise<DesktopCapturerSource[]>
,异步的,回调函数外面的
console.log(_self.picPath)
拿不到结果