Electron with Vue 框架搭建及打印功能分享
2019.09.27
文档有改进地方,欢迎提出。
安装
-
准备工作:确保本机已经安装了nodejs && npm
-
检查本地是否已经安装了vue:
npm view vue version
;否则先安装vue:npm install vue
-
创建一个electron-vue的demo项目:
vue create electron-vue-demo
-
安装配置:
? Please pick a preset: default (babel, eslint) > Manually select features
? Check the features needed for your project: (*) Babel ( ) TypeScript ( ) Progressive Web App (PWA) Support (*) Router (*) Vuex >(*) CSS Pre-processors (*) Linter / Formatter ( ) Unit Testing ( ) E2E Testing
Use history mode for router? (Requires proper server setup for index fallback in production) (Y/n) y
? Pick a CSS pre-processor (PostCSS, Autoprefixer and CSS Modules are supported by default): Sass/SCSS (with dart-sass) Sass/SCSS (with node-sass) > Less Stylus
? Pick a linter / formatter config: (Use arrow keys) > ESLint with error prevention only ESLint + Airbnb config ESLint + Standard config ESLint + Prettier
? Pick a linter / formatter config: (Use arrow keys) > ESLint with error prevention only ESLint + Airbnb config ESLint + Standard config ESLint + Prettier
? Pick additional lint features: (Press <space> to select, <a> to toggle all, <i> to invert selection) >(*) Lint on save ( ) Lint and fix on commit (requires Git)
? Where do you prefer placing config for Babel, PostCSS, ESLint, etc.? (Use arrow keys) > In dedicated config files In package.json
Save this as a preset for future projects? (y/N) N
此处安装过程需要大约2分钟(视网络决定)
-
进入项目目录:
cd electron-vue-demo
-
启动 Vue.js App 项目:
npm run serve
,打开浏览器登入:http://localhost:8080/ -
安装electron构建包:
vue add electron-builder
使用打印机必须要使用electron 3.0或以下版本,此处先任意选择安装,后续单独更换electron版本。
npm uninstall electron && npm install electron@3.1.13 --save-dev
? Choose Electron Version (Use arrow keys) ^4.0.0 ^5.0.0 > ^6.0.0
electron包文件较大,此处安装过程耗时较长,建议使用淘宝镜像cnpm安装。
-
由于electron将版本的问题,
./src/background.js
中有一处需要更改配置,否则启动不了electron。//删除第15行: // protocol.registerSchemesAsPrivileged([{scheme: 'app', privileges: { secure: true, standard: true } }]) //新增一行: protocol.registerStandardSchemes(['app'], { secure: true })
-
启动electron项目:
npm run electron:serve
-
默认配置了热加载,代码保存后,electron窗口会体现最新效果。
搭建框架
-
安装axios:
npm install axios --save-dev
-
封装数据请求方法:
新建文件夹:
./src/axios/
新建文件并粘贴代码:
api.js
import requestAll from "./request"; //引用fetch,js import apiHeader from './url'; //引用url.js // 数据请求 export function Axios(method, api, params = { }) { let header = ''; header = apiHeader.server; // 浏览器访问 if( !window.require ) { header = '/api'; } // electron访问 return requestAll.Request(header+api, params, method) }
request.js
import axios from 'axios';//引入axios // post请求 function Request(url, data = { }, method = 'post') { return new Promise((resolve, reject) => { axios({ url: url, method: method, headers: { 'Content-Type': 'application/json' }, timeout: 30 * 1000, // 30秒超时 data: data }) .then(res => { // 统一错误状态码 let errorMessage =