我正在使用Vue和Electron构建桌面应用。我想从vue组件中保存一个文件,其中包含用户引入的一些数据。为此,我尝试在vuex操作中使用fs节点模块,但它让我犯了错误。无法找到该模块。我知道Vue是客户端,但是,我认为在使用Electron的那一刻它可以工作,但确实如此。要初始化我的应用程序,我使用了vue-cli和命令vue init webpack electron-vue。 我也使用vuex系统并使用vuex模块,我还有一个actions.js文件,我尝试使用fs模块:
// import * as fs from 'fs'; I used this way at first
const fs = require('fs');
export const writeToFile = ({commit}) => {
fs.writeFileSync('/path/file.json', JSON.stringify(someObjectHere));
};
当我从Vue组件ex,Options.vue调用此操作时,我使用vuex调度系统,并且在该组件的created()方法中:
this.$store.dispatch('writeToFile')
这引起了我上面提到的错误
答案 0 :(得分:2)
使用Vue和WebPack中的电子文件系统,执行命令“npm run build”后,必须在dist / index.html中声明文件系统实例
<script>
var fs = require('fs');
</script>
并且在vue组件中,如果它已在vue文件中声明,则使用fs。
...
export const writeToFile = ({commit}) => {
fs.writeFileSync('/path/file.json', SON.stringify(someObjectHere))
};
...
虽然如果不在电子中使用它或者你在dev的索引中写它,它会抛出错误。
答案 1 :(得分:0)
使用window.require
会有所帮助。这是“ App.vue”文件的<script></script>
部分:
import HelloWorld from './components/HelloWorld'
function writeToFileSync(filepath, content) {
if (window && window.require) {
const fs = window.require('fs')
fs.writeFileSync(filepath, content)
}
}
writeToFileSync('/usr/local/worktable/sandbox/msg.txt', 'Hello\nworld')
export default {
name: 'App',
components: {
HelloWorld
},
data: () => ({
//
})
}
上面的代码在以下位置进行测试:
nodeIntegration
设置为true)vue create
生成)