Electron+vue聊天仿微信界面|electron-vue聊天实践

孤人 提交于 2020-02-27 15:43:14

简介

electron-vchat实践聊天项目是基于electron+vue+electron-vue+vuex+Node技术开发的仿微信客户端界面聊天室。有实现消息发送/表情,图片/视频预览,拖拽上传/粘贴截图发送/微信dll截图,右键菜单、朋友圈/红包/换肤等功能。

效果图

技术架构

  • 框架技术:electron + electron-vue + vue
  • 状态管理:Vuex
  • 地址路由:Vue-router
  • 字体图标:阿里iconfont字体图标库
  • 弹窗插件:wcPop
  • 打包工具:electron-builder
  • 图片预览:vue-photo-preview
  • 视频组件:vue-video-player
/**
 * @Desc   公共及全局组件配置
 * @about  Q:282310962  wx:xy190310
 */

// 引入公共组件
import winBar from './components/winbar'
import sideBar from './components/sidebar'

// 引入公共样式
import './assets/fonts/iconfont.css'
import './assets/css/reset.css'
import './assets/css/layout.css'

// 引入弹窗wcPop
import wcPop from './assets/js/wcPop/wcPop'
import './assets/js/wcPop/skin/wcPop.css'

// 引入图片预览组件vue-photo-preview
import photoView from 'vue-photo-preview'
import 'vue-photo-preview/dist/skin.css'

// 引入视频播放组件vue-video-player
import videoPlayer from 'vue-video-player'
import 'video.js/dist/video-js.css'

const install = Vue => {
    // 注册组件
    Vue.component('win-bar', winBar)
    Vue.component('side-bar', sideBar)

    // 应用实例
    Vue.use(photoView, {
        // loop: false, //循环
        // fullscreenEl: true, //全屏
        // arrowEl: true, //左右按钮
    })
    Vue.use(videoPlayer)
}

export default install

Electron 是由 Github 开发,用 HTML,CSS 和 JavaScript 来构建跨平台桌面应用程序的一个开源库。至于如何搭建项目这里不多介绍,去官网查阅即可。

https://electronjs.org/

https://github.com/SimulatedGREG/electron-vue

electron 主进程创建窗体

通过 electron 里的 BrowserWindow 对象创建和控制浏览器窗口

import { BrowserWindow, app, ipcMain, Tray, Menu } from 'electron'

// 引入主线程公共配置
import Common from './utils/common'

/**
 * Set `__static` path to static files in production
 * https://simulatedgreg.gitbooks.io/electron-vue/content/en/using-static-assets.html
 */
if (process.env.NODE_ENV !== 'development') {
  global.__static = require('path').join(__dirname, '/static').replace(/\\/g, '\\\\')
}

let mainWin
let tray
let forceQuit = false
let logined = false

/**
 * 创建主窗口=============================
 */
function createMainWin() {
  mainWin = new BrowserWindow({
    // 背景颜色
    // backgroundColor: '#ebebeb',
    width: Common.WIN_SIZE_MAIN.width,
    height: Common.WIN_SIZE_MAIN.height,
    title: Common.WIN_TITLE,
    useContentSize: true,
    autoHideMenuBar: true,
    // 无边框窗口
    frame: false,
    resizable: true,
    // 窗口创建的时候是否显示. 默认值为true
    show: false,
    webPreferences: {
      // devTools: false,
      webSecurity: false
    }
  })

  mainWin.setMenu(null)
  mainWin.loadURL(Common.WIN_LOAD_URL())

  mainWin.once('ready-to-show', () => {
    mainWin.show()
    mainWin.focus()
  })

  mainWin.on('close', (e) => {
    if(logined && !forceQuit) {
      e.preventDefault()
      mainWin.hide()
    }else {
      mainWin = null
      app.quit()
    }
  })

  initialIPC()
}

app.on('ready', createMainWin)

app.on('activate', () => {
  if(mainWin === null) {
    createMainWin()
  }
})

app.on('before-quit', () => {
  forceQuit = true
})

app.on('window-all-closed', () => {
  if(process.platform !== 'darwin') {
    app.quit()
  }
})

electron实现系统托盘图标+图标闪烁+右键菜单

electron通过Tray、Menu对象来创建托盘图标及右键

/**
 * 托盘图标事件
 */
let flashTrayTimer = null
let trayIco1 = `${__static}/icon.ico`
let trayIco2 = `${__static}/empty.ico`
let apptray = {
  // 创建托盘图标
  createTray() {
    tray = new Tray(trayIco1)
    const menu = Menu.buildFromTemplate([
      {
        label: '打开主界面',
        icon: `${__static}/tray-ico1.png`,
        click: () => {
          if(mainWin.isMinimized()) mainWin.restore()
          mainWin.show()
          mainWin.focus()
          
          this.flashTray(false)
        }
      },
      {
        label: '关于',
      },
      {
        label: '退出',
        click: () => {
          if(process.platform !== 'darwin') {
            mainWin.show()
            // 清空登录信息
            mainWin.webContents.send('clearLoggedInfo')
            
            forceQuit = true
            mainWin = null
            app.quit()
          }
        }
      },
    ])
    tray.setContextMenu(menu)
    tray.setToolTip('electron-vchat v1.0.0')

    // 托盘点击事件
    tray.on('click', () => {
      if(mainWin.isMinimized()) mainWin.restore()
      mainWin.show()
      mainWin.focus()

      this.flashTray(false)
    })
  },
  // 托盘图标闪烁
  flashTray(bool) {
    let hasIco = false

    if(bool) {
      if(flashTrayTimer) return
      flashTrayTimer = setInterval(() => {
        tray.setImage(hasIco ? trayIco1 : trayIco2)
        hasIco = !hasIco
      }, 500)
    }else {
      if(flashTrayTimer) {
        clearInterval(flashTrayTimer)
        flashTrayTimer = null
      }

      tray.setImage(trayIco1)
    }
  },
  // 销毁托盘图标
  destroyTray() {
    this.flashTray(false)
    tray.destroy()
    tray = null
  }
}

electron无边框窗体拖动、自定义顶部栏

// 置顶窗口
handleFixTop() {
	this.isAlwaysOnTop = !this.isAlwaysOnTop
	currentWin.setAlwaysOnTop(this.isAlwaysOnTop)
},

// 最小化
handleMin() {
	currentWin.minimize()
},

// 最大化
handleMax() {
	if(!currentWin.isMaximizable()) return
	if(currentWin.isMaximized()) {
		currentWin.unmaximize()
		this.SET_WINMAXIMIZE(false)
	}else {
		currentWin.maximize()
		this.SET_WINMAXIMIZE(true)
	}
},

通过设置 -webkit-app-region: drag 进行局部拖动

注意:默认设置 -webkit-app-region: drag 后,下面的元素不能点击操作,可通过设置需点击元素 no-drag 即可。

electron实现 contenteditable="true" 双向绑定、光标处插入表情

vue中设置div可编辑contenteditable="true" 自定义双向绑定v-model ,定位光标处插入动态表情。

大家可以去参阅之前的这篇分享:https://juejin.im/post/5e141ffc5188253a57049a63

electron+vue实现可编辑框粘贴截图发送图片

// 可编辑div contenteditable中粘贴发送图片
handlePastImage {
	let that = this
	this.$refs.editor.addEventListener('paste', function(e) {
		let cbd = e.clipboardData
		let ua = window.navigator.userAgent
		if(!(e.clipboardData && e.clipboardData.items)) return
		
		if(cbd.items && cbd.items.length === 2 && cbd.items[0].kind === "string" && cbd.items[1].kind === "file" &&
			cbd.types && cbd.types.length === 2 && cbd.types[0] === "text/plain" && cbd.types[1] === "Files" &&
			ua.match(/Macintosh/i) && Number(ua.match(/Chrome\/(\d{2})/i)[1]) < 49){
			return;
		}
		for(var i = 0; i < cbd.items.length; i++){
			var item = cbd.items[i];
			console.log(item);
			console.log(item.kind);
			if(item.kind == "file"){
				var blob = item.getAsFile();
				if(blob.size === 0){
					return;
				}
				// 插入图片记录
				var reader = new FileReader();
				reader.readAsDataURL(blob);
				reader.onload = function(){
					var _img = this.result;

					// ***返回图片给父组件
					that.$emit('pasteFn', _img)
				}
			}
		}
	})
},

好了,基于electron+vue桌面版聊天实践分享就到这里,希望有点点帮助~~

最后送上两个最新多端(Uniapp、Taro)聊天实例:

基于vue+uniapp直播项目|uni-app仿抖音/陌陌直播室

Taro聊天室|react+taro仿微信聊天App界面|taro聊天实例

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!