整合營銷服務商

          電腦端+手機端+微信端=數據同步管理

          免費咨詢熱線:

          Electron 13結合Vuejs3創建桌面應用程序-環境搭建篇

          Electron + vue3

          1.Electronjs

          electron概念:

          Electron 是一個基于Chromium 和 Node.js實現的桌面應用框架,可以使用 JavaScript, HTML 和 CSS 等 Web 技術構建原生程序,例如vscode、skype、whatsapp等都是基于electronjs框架開發的。

          electron優點:

          • 跨平臺,開源免費,社區活躍,一次編寫,Windows、Mac、Linux都能運行。
          • 熟練前端三劍客html、css、js即可構建應用。
          • 可通過node.js、原生native api 增強web功能體驗。
          • 內置chromium瀏覽器,兼容性好,支持html5 css3 es6+語法

          2.Vuejs

          vue概念:

          Vue.js是一套構建用戶界面的漸進式JavaScript框架,是目前流行前端三大框架之一。

          vue優點:

          • 組件化開發,使冗余代碼編寫量大大減少,易維護。
          • 數據雙向綁定,響應式開發,配合vuejs devtools瀏覽器插件開發效率高。
          • 虛擬dom,數據和結構的分離,結構清晰。
          • 單頁面應用,頁面局部刷新,運行速度更快。

          環境搭建

          1.nodejs準備工作

          安裝nodejs LTS(長期支持版本),安裝完終端查看版本。

          J:\test\electronjs>node -v
          v14.16.0
          J:\test\electronjs>npm -v
          7.19.1

          2.安裝cnpm 或者 yarn

          推薦使用全局安裝cnpm,并配置淘寶源

          npm install cnpm -g
          cnpm config set registry https://registry.npm.taobao.org

          安裝完查看源設置是否成功

          J:\test\electronjs>cnpm config get registry
          https://registry.npm.taobao.org/

          3.安裝vue-cli4環境

          cnpm install @vue/cli -g

          安裝完查看vue-cli版本

          J:\test\electronjs>vue -V
          @vue/cli 4.5.13

          4.創建vue3項目

          J:\test\electronjs>vue create vueproj1
          
          # 點最后一項 手動選擇安裝
          ? Please pick a preset:
            Default ([Vue 2] babel, eslint)
            Default (Vue 3) ([Vue 3] babel, eslint)
          > Manually select features
          
          # 選擇項目要使用的特性模塊,空格勾選模塊,選擇完成 回車確認下一步
          ? Check the features needed for your project:
           (*) Choose Vue version
           (*) Babel
           ( ) TypeScript
           ( ) Progressive Web App (PWA) Support
          >(*) Router
           (*) Vuex
           (*) CSS Pre-processors
           (*) Linter / Formatter
           ( ) Unit Testing
           ( ) E2E Testing
          
          # 選擇3.x版本,回車下一步
          ? Choose a version of Vue.js that you want to start the project with
            2.x
          > 3.x
          
          # 這里選擇路由是否使用歷史模式,這里選擇n,需要使用hash模式
          ? Use history mode for router? (Requires proper server setup for index fallback in production) (Y/n) n
          
          # 這里選擇 默認第一項css預處理器
          ? Pick a CSS pre-processor (PostCSS, Autoprefixer and CSS Modules are supported by default): (Use arrow keys)
          > 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 additional lint features: (Press <space> to select, <a> to toggle all, <i> to invert selection)
          >(*) Lint on save
           ( ) Lint and fix on commit
          
          # 選擇第一項即可,放在專用的配置文件中
          ? Where do you prefer placing config for Babel, ESLint, etc.? (Use arrow keys)
          > In dedicated config files
            In package.json
          
          # 是否保存到預設給將來項目,y的話會存到.vuerc中,這里選N,等待完成創建
          ? Save this as a preset for future projects? (y/N) N
          

          5.基于vue3項目搭建electron環境

          # 進到剛才創建的項目目錄中
          J:\test\electronjs>cd vueproj1
          
          # 使用electron-builder構建 基于vue3的electron環境
          J:\test\electronjs\vueproj1>vue add electron-builder
          
          # 目前支持到13版本,我們選擇13
          ? Choose Electron Version (Use arrow keys)
            ^11.0.0
            ^12.0.0
          > ^13.0.0
          
          # 安裝完 我們檢查 electron 版本
          J:\test\electronjs\vueproj1>npx electron -v
          v13.3.0

          6.啟動開發服務

          # 開發模式,實時預覽
          npm run electron:serve
          
          # 編譯打包
          npm run electron:build

          效果圖如下:

          項目優化:

          開發環境 啟動優化:

          # 首次 運行服務后,默認是有請求安裝 vue devtools插件
          INFO  Launching Electron...
          > Failed to fetch extension, trying 4 more times
          Failed to fetch extension, trying 3 more times
          Failed to fetch extension, trying 2 more times
          Failed to fetch extension, trying 1 more times
          Failed to fetch extension, trying 0 more times
          Vue Devtools failed to install: Error: net::ERR_CONNECTION_TIMED_OUT

          解決思路:

          1.搭建vpn可以訪問國外網絡。

          2.修改background.js主進程代碼,注釋掉 devtools相關代碼

          // 1.開發工具引入 這塊注釋
          // import installExtension, { VUEJS3_DEVTOOLS } from 'electron-devtools-installer'
          ...
          // 2.應用準備好 開發環境 嘗試安裝擴展 這塊注釋
          app.on('ready', async () => {
            // if (isDevelopment && !process.env.IS_TEST) {
            //   // Install Vue Devtools
            //   try {
            //     await installExtension(VUEJS3_DEVTOOLS)
            //   } catch (e) {
            //     console.error('Vue Devtools failed to install:', e.toString())
            //   }
            // }
            createWindow()
          })

          electron配置預加載preload.js

          electron 窗口創建時支持預加載腳本,預加載preload.js腳本處于渲染進程中,支持nodejs 語法

          1.在src目錄下 創建 preload.js,添加如下代碼:

          // All of the Node.js APIs are available in the preload process.
          // It has the same sandbox as a Chrome extension.
          
          const {contextBridge, nativeImage, ipcRenderer} = require('electron');
          
          contextBridge.exposeInMainWorld(
              'electron',
              {
                  nativeImage,
                  ipcRenderer,
              }
          )

          2.在electron主進程 background.js 中配置上步創建的預加載js

          // 引入node path模塊
          const path = require('path')
          ...
          
          const win = new BrowserWindow({
              width: 800,
              height: 600,
              webPreferences: {
                  ...
                  // 窗口創建web首選項 新增如下配置
                  
                  // electron:nativeWindowOpen的默認值已被棄用,并將在electron 15中從false更改為true。
                  nativeWindowOpen: true,
                  
                  // 開啟遠程模塊
                  enableRemoteModule: true,
                  
                  // 預加載配置,這里用到上面的path模塊
                  preload: path.join(__dirname, 'preload.js'),
              }
          })

          3.在項目根目錄,創建 vue.config.js 并增加如下代碼:

          module.exports = {
              pluginOptions: {
                  electronBuilder: {
                      preload: 'src/preload.js',
                  }
              }
          }

          electron遠程模塊remote優化

          remote模塊在 Electron 12 中被棄用,并將在 Electron 14 中移除。它被@electron/remote模塊取代 。

          1.安裝擴展。

          cnpm install --save @electron/remote

          2.安裝完成 先在主進程 src/background.js 中 增加如下

          // in the main process:
          require('@electron/remote/main').initialize()
          ...

          3.擴展進程預加載 preload.js 添加如下代碼:

          將常用的remote模塊,通過上下文橋梁(contextBridge)暴露給渲染器,頁面可以使用window.electron.remote調用

          // All of the Node.js APIs are available in the preload process.
          // It has the same sandbox as a Chrome extension.
          
          const {contextBridge, nativeImage, ipcRenderer} = require('electron');
          const remote = require('@electron/remote');
          
          contextBridge.exposeInMainWorld(
              'electron',
              {
                  nativeImage,
                  ipcRenderer,
                  remote
              }
          )

          演示示例(調起對話框)

          修改默認視圖頁面組件 src/views/Home.vue

          <template>
            <div class="home">
              <img alt="Vue logo" src="../assets/logo.png">
              <br />
              <button @click="myDialog">點擊打開系統對話框</button>
          <!--    <HelloWorld msg="Welcome to Your Vue.js App"/>-->
            </div>
          </template>
          
          <script>
          // @ is an alias to /src
          // import HelloWorld from '@/components/HelloWorld.vue'
          
          export default {
            name: 'Home',
            components: {
              // HelloWorld
            },
            methods: {
              myDialog(){
                // 通過preload.js 上下文暴露的remote對象
                window.electron.remote.dialog.showMessageBox({
                  title: '系統對話框',
                  type: 'info',
                  message: '測試下系統對話框'
                })
              }
            }
          }
          </script>
          

          效果如下:

          以上就是Electron13 + Vue3 搭建環境篇內容,后續推出更多的相關文章,大家敬請期待~

          .背景:
          即時通訊、桌面端app開發、當用戶和用戶聊天,當發送聊天消息時,須要作收到消息通知,因為用到的技術棧是electron、它也有自己的通知模塊、因為其他的原因暫時用不了 最后查到HTML5新增的 Notification API的通知功能。即便將瀏覽器窗口最小化,依然會收到消息通知、所以就先用它吧、后面再后話處理一下。

          2.通知權限:
          2.1 首先須要 看瀏覽器是否支持 Notification ,支持才有下文,不然就此止步;
          2.2 經過 Notification.permission 檢測用戶是否容許通知:

          // Notification.permission === 'granted' 用戶容許
          // Notification.permission === 'denied' 用戶拒絕
          // Notification.permission === 'denied' 不知道用戶的選擇,默認
          
          if(Notification.permission === 'granted'){
              console.log('用戶容許通知');
              instance_init(title, options);
          }else if(Notification.permission === 'denied'){
              console.log('用戶拒絕通知');
          }else{
              console.log('用戶還沒選擇,去向用戶申請權限吧');
              Notification.requestPermission(function(status) {
              	if(status=='granted'){
              		console.log('用戶容許通知');
              		instance_init(title, options);
              	}else if(status=='denied'){
              		console.log('用戶拒絕通知');
              	}else{
              		console.log('用戶還沒選擇');
              	}
              });
          }

          3. 主要用到的參數。其他參數了解:notification - Web API 接口參考 | MDNMDN Web DocsMDN logoMozilla logo

          title:通知的標題
          options:通知的設置選項(可選)。
          	body:通知的內容。
          	tag:表明通知的一個識別標簽,相同tag時只會打開同一個通知窗口。
          	icon:要在通知中顯示的圖標的URL。
          	image:要在通知中顯示的圖像的URL。
          	data:想要和通知關聯的任務類型的數據。
          	requireInteraction:通知保持有效不自動關閉,默認為false。

          4.代碼實現

          4.1原生html5方式

          <html>
          
          	<head>
          		<meta charset="UTF-8">
          		<title>H5通知功能 </title>
          	</head>
          
          	<body>
          		<script type="text/javascript">
          			// 調用通知方法
          			showMsgNotification('狀態更新提醒','你的朋友圈有3條新狀態,快去查看吧');
          			/**
          			 * H5通知功能 
          			 */
          			function showMsgNotification(out_title, out_msg) {
          				var title = out_title ? out_title : '更新狀態標題';
          				var options = {
          					body: out_msg ? out_msg : "更新狀態內容", // 通知主體
          					requireInteraction: true, // 不自動關閉通知
          					icon: 'http://img18.house365.com/newcms/2017/03/16/148964317858ca26aacf7b5.jpg', // 通知圖標 
          					tag: 'hangge',
          				};
          				var Notification = window.Notification || window.mozNotification || window.webkitNotification; // 瀏覽器作兼容處理
          				if(Notification) { //支持桌面通知
          					if(Notification.permission == "granted") { //已經容許通知
          						instance_init(title, options);
          					} else {
          						//第一次詢問或已經禁止通知(若是用戶以前已經禁止顯示通知,那么瀏覽器不會再次詢問用戶的意見,Notification.requestPermission()方法無效)
          						Notification.requestPermission(function(status) {
          							if(status === "granted") { //用戶容許
          								instance_init(title, options);
          							} else { //用戶禁止
          								console.log('禁止')
          								return false
          							}
          						});
          					}
          					/**
          					 * Notification定義
          					 * */
          					function instance_init(title, options){
          						var instance = new Notification(title, options);
          						instance.onclick = function() {
          							console.log('onclick');
          							// 關閉通知
          							instance.close();
          						};
          						instance.onerror = function() {
          							console.log('onerror');
          						};
          						instance.onshow = function() {
          							console.log('onshow');
          						};
          						instance.onclose = function() {
          							console.log('onclose');
          						};
          					}
          				} else { //不支持(IE等)
          					console.log("不支持的瀏覽器")
          				}
          			}
          		</script>
          	</body>
          
          </html>

          4.2 electron方式、調用即可

          周GitHub排行精選

          edex-ui

          eDEX-UI 是一個全屏桌面應用程序,類似于科幻電腦界面,其靈感來自于DEX-UI和TRON Legacy電影特效。

          本周 star 3082

          開源項目地址:https://github.com/GitSquared/edex-ui

          Big List of Naughty Strings

          Big List of Naughty Strings (淘氣字符串大列表)是一個持續更新的字符串列表,包括了那些在輸入區域很可能就引發問題的字符串,由 Max Woolf 發起和維護。這個列表可用于自動或手工 QA 測試。

          本周 star 2690

          開源項目地址:https://github.com/minimaxir/big-list-of-naughty-strings

          nginxconfig.io

          一個在線nginx配置生成器。

          本周 star 2497

          開源項目地址:https://github.com/valentinxxx/nginxconfig.io

          Doodle Master

          涂鴉大師試圖將你的UI模型轉換成真實的代碼。目前,這個存儲庫只是為了證明人工智能設計工具的概念。

          本周 star 2116

          開源項目地址:https://github.com/karanchahal/DoodleMaster

          Lorca

          一個非常小的庫,用于在 Go 中構建 HTML5 桌面應用程序。它使用Chrome瀏覽器作為UI層。與電子產品不同的是,它沒有將 Chrome 捆綁到應用程序包中,而是重用已經安裝的應用程序。

          本周 star 1445

          開源項目地址:https://github.com/zserge/lorca

          Wayne

          Wayne 是一個通用的、基于 Web 的 Kubernetes 多集群管理平臺。通過可視化 Kubernetes 對象模板編輯的方式,降低業務接入成本, 擁有完整的權限管理系統,適應多租戶場景,是一款適合企業級集群使用的發布平臺。

          本周 star 1324

          開源項目地址:https://github.com/Qihoo360/wayne

          關注 wx - 公 - 號 -:非著名程序員,對話框回復關鍵字 “1024”,免費領取 30 本經典編程書籍。


          主站蜘蛛池模板: 国产福利电影一区二区三区久久老子无码午夜伦不 | 成人精品一区二区三区不卡免费看| 久久精品中文字幕一区| 亚洲av无码片区一区二区三区| 相泽亚洲一区中文字幕| 国产萌白酱在线一区二区| 一区高清大胆人体| 亚洲AV日韩AV天堂一区二区三区| 全国精品一区二区在线观看| 成人一区专区在线观看| 色婷婷香蕉在线一区二区| 亚拍精品一区二区三区| 91久久精品午夜一区二区| 亚洲一区二区在线免费观看| 伊人久久大香线蕉av一区| 亚洲一区二区三区在线观看精品中文 | 日韩一区二区在线免费观看| 亚洲乱色熟女一区二区三区蜜臀| 精品一区二区三区免费毛片爱| 亚洲永久无码3D动漫一区| 中文字幕在线无码一区二区三区 | 国产一区二区视频在线观看| 日韩视频在线观看一区二区| 无码精品久久一区二区三区| 日本一区二区三区中文字幕| 中文字幕无线码一区2020青青| 日韩人妻一区二区三区免费 | av无码一区二区三区| 好湿好大硬得深一点动态图91精品福利一区二区 | 日韩精品无码中文字幕一区二区| 看电影来5566一区.二区| 国产av一区二区三区日韩| 午夜福利一区二区三区高清视频| 日韩精品一区二区亚洲AV观看 | 亚洲国产综合精品一区在线播放| 丰满岳乱妇一区二区三区| 一区二区三区日本电影| 日韩制服国产精品一区| 日韩精品视频一区二区三区| 91视频国产一区| 成人一区专区在线观看|