返回

Electron+Vue构建桌面端日期时间倒计时软件实践

前端

引言

在现代社会,日期和时间管理尤为重要。一个直观易用的日期时间倒计时软件可以帮助我们高效地安排行程,合理规划时间。本文将深入探讨如何使用Electron和Vue构建这样一个功能强大的桌面端日期时间倒计时软件,为开发者提供实用的开发指南。

1. 环境搭建

首先,我们需要搭建开发环境。本文推荐使用Node.js版本为16.13.0或以上、Electron版本为19.0.6或以上、Vue版本为3.2.30或以上。此外,需要安装Electron和Vue的CLI工具:

npm install -g electron
npm install -g @vue/cli

2. 创建项目

使用Vue CLI创建新的Electron项目:

vue create my-countdown-app --template electron-builder

进入项目目录:

cd my-countdown-app

运行项目:

npm run dev

3. 主题适配

为了适配不同的系统主题,我们需要在Electron的主进程文件中进行设置:

// main.js
const { app, BrowserWindow } = require('electron')

app.whenReady().then(() => {
  createWindow()

  app.on('activate', function () {
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
  })
})

function createWindow () {
  const win = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      nodeIntegration: true
    }
  })

  win.loadFile('index.html')
}

4. 新建窗口

当用户点击"添加"按钮时,我们需要新建一个窗口:

// renderer.js
const { app, BrowserWindow } = require('electron')

Vue.component('app', {
  template: `
    <div>
      <button @click="addWindow">添加</button>
    </div>
  `,
  methods: {
    addWindow() {
      const win = new BrowserWindow({
        width: 400,
        height: 300,
        webPreferences: {
          nodeIntegration: true
        }
      })

      win.loadFile('window.html')
    }
  }
})

5. 本地化存储

我们需要使用Electron的存储API来管理本地数据:

// main.js
const { app, BrowserWindow } = require('electron')
const path = require('path')

app.whenReady().then(() => {
  createWindow()

  app.on('activate', function () {
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
  })
})

function createWindow () {
  const win = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      nodeIntegration: true
    }
  })

  win.loadFile('index.html')

  // 存储数据
  win.webContents.session.storageData[(localStorage/sessionStorage)].setItem('key', 'value')

  // 读取数据
  const value = win.webContents.session.storageData[(localStorage/sessionStorage)].getItem('key')
}

6. 托盘图标

我们可以使用Electron的托盘API来设置托盘图标:

// main.js
const { app, Tray, Menu } = require('electron')

app.whenReady().then(() => {
  const tray = new Tray('icon.png')
  const contextMenu = Menu.buildFromTemplate([
    { label: 'Item 1' },
    { label: 'Item 2' }
  ])
  tray.setContextMenu(contextMenu)
})

7. 右键菜单

我们可以使用Electron的上下文菜单API来设置右键菜单:

// renderer.js
const { remote } = require('electron')

Vue.component('app', {
  template: `
    <div>
      <button @contextmenu="showContextMenu">右键菜单</button>
    </div>
  `,
  methods: {
    showContextMenu(e) {
      const menu = remote.Menu.buildFromTemplate([
        { label: 'Item 1' },
        { label: 'Item 2' }
      ])
      menu.popup({ window: remote.getCurrentWindow() })
    }
  }
})

8. 实际案例

现在,让我们构建一个实际的日期时间倒计时功能:

// renderer.js
const { remote } = require('electron')

Vue.component('countdown', {
  template: `
    <div>
      <input v-model="date" type="date">
      <input v-model="time" type="time">
      <button @click="start">开始</button>
      <button @click="stop">停止</button>
      <p>{{ remainingTime }}</p>
    </div>
  `,
  data() {
    return {
      date: '',
      time: '',
      remainingTime: '',
      interval: null
    }
  },
  methods: {
    start() {
      const targetDate = new Date(`${this.date} ${this.time}`)
      this.interval = setInterval(() => {
        const now = new Date()
        const remaining = targetDate - now
        if (remaining <= 0) {
          clearInterval(this.interval)
          this.remainingTime = '时间已到'
        } else {
          this.remainingTime = this.formatTime(remaining)
        }
      }, 1000)
    },
    stop() {
      clearInterval(this.interval)
    },
    formatTime(ms) {
      const days = Math.floor(ms / (1000 * 60 * 60 * 24))
      const hours = Math.floor((ms / (1000 * 60 * 60)) % 24)
      const minutes = Math.floor((ms / (1000 * 60)) % 60)
      const seconds = Math.floor((ms / 1000) % 60)
      return `${days}${hours}小时 ${minutes}分钟 ${seconds}秒`
    }
  }
})

结论

本文详细介绍了如何使用Electron和Vue构建一个功能强大的桌面端日期时间倒计时软件,涵盖了主题适配、新建窗口、本地化存储、托盘图标、右键菜单等知识点。通过本文,开发者可以了解如何构建自己的Electron应用,并为桌面用户提供更加丰富的体验。