Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

如题,我使用了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) // 打印 ''
      }
    })
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
487 views
Welcome To Ask or Share your Answers For Others

1 Answer

desktopCapturer.getSources返回Promise<DesktopCapturerSource[]>,异步的,
回调函数外面的console.log(_self.picPath) 拿不到结果


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...