使用 Vue.js 2 + Electron 开发桌面应用

随着 JavaScript 开源社区的发展,JavaScript 的应用场景越来越广泛,到目前为止,JavaScript 在Web开发、桌面开发、APP开发、服务端开发方面都可以胜任。

在桌面开发方面,如果你熟悉 C#或 Java 等技术,你就知道构建桌面应用程序的复杂,有时可能需要自己编写 DLL(动态链接库)文件。而 Electron 则基于 HTML、CSS、JavaScript,并且是跨平台的。目前有很多优秀的桌面软件都是使用 Electron 开发的:

微软的 VSCode 也是基于 Electron 开发的,居然没用自己的开发套件,可见 Electron 的桌面解决方案的优秀。

What We Will Build

We will be building a desktop application that allows people to take quiz questions, and at the end of the questions, see their total score.

Getting Started With The Vue-Cli

To get started easily and also skip the process of configuring Webpack for the compilation from ES2016 to ES15, we will use the Vue CLI.

vue init webpack electron-vue
//change directory into the folder
cd electron-vue
//install the npm dependencies
npm install

After installing these modules, we need to install Electron on our system.

Installing And Configuring Electron

I usually prefer running Electron globally, but you can install locally.
To install globally, we can run:

npm install -g electron

To install locally, we can run:

npm install electron

Let's move into our package.json file which has been created by our vue-cli and add a new line to it under the first object block, which defines name, version, description, author, private. Just before the scripts also, we would add a key pair called "main" with a value of "elect.js" .

"name": "electron-vue",
"version": "1.0.0",
"description": "A Vue.js project",
"author": "zhangyongjie <1091354206@qq.com>",
"private": true,
"main": "elect.js",
"scripts": {
    "dev": "node build/dev-server.js",
    "start": "node build/dev-server.js",
    "build": "node build/build.js"
},

We have defined elect.js as the starting point for Electron to run its application, so in our root folder, we will create a file called elect.js and put in the following content:

const {
    app,
    BrowserWindow
} = require('electron')

let win = null;

app.on('ready', function () {

    // Initialize the window to our specified dimensions
    win = new BrowserWindow({
        width: 1000,
        height: 600
    });

    // Specify entry point to default entry point of vue.js
    win.loadURL('http://localhost:8080');

    // Remove window once app is closed
    win.on('closed', function () {
        win = null;
    });

});

//create the application window if the window variable is null
app.on('activate', () => {
    if (win === null) {
        createWindow()
    }
});

//quit the app once closed
app.on('window-all-closed', function () {
    if (process.platform != 'darwin') {
        app.quit();
    }
});

The main focus here is the ready event, where we set a new dimension for our app, load the entry point, which could be a direct URL or a file URL. But for now, we are loading the development URL for Vue.

At this point, we can open up two terminals to the root of our project.

In the first terminal, we want to serve our Vue application, So we run:

npm run dev

On the second terminal, we want to run the Electron application, so we run:

electron .

If all goes well, we should be seeing this:

Creating The Quiz Application

It's time to move into our src/App.vue to do the main quiz application.

<template>
    <div id="app">
        <!-- Questions: display a div for each question -->
        <!-- show only if the index of the quetion is equal to the question index -->
        <div v-for="(quiz, index) in quizez" v-show="index === questionindex">
            <!-- display the quiz Category -->
            <h1>{{ quiz.category }}</h1>
            <!-- display the quiz question -->
            <h2>{{ quiz.question }}</h2>
            <!-- Responses: display a li for each possible response with a radio button -->
            <ol>
                <!--display the quiz options -->
                <li v-for="answer in quiz.answers">
                    <label>
                        <!-- bind the options to the array index of the answers array that matches this index -->
                        <input type="radio" name="answer" v-model="answers[index]" :value="answer"> {{answer}}
                    </label>
                </li>
            </ol>
    
        </div>
        <!-- do not display if the question index exceeds the length of all quizez -->
        <div v-if="questionindex < quizez.length">
            <!-- display only if the question index is greater than zero -->
            <!-- onclick of this button, show last question -->
            <button v-if="questionindex > 0" @click="questionindex-=1">
                prev
            </button>
            <!-- onclick of this button, and show next question -->
            <button @click="questionindex+=1">
                next
            </button>
        </div>
        <!-- show total score, if the questions are completed -->
        <span v-if="questionindex == quizez.length">Your Total score is {{score}} / {{quizez.length}}</span>
    </div>
</template>

<script>
// an array of questions to be asked. Length of 5 questions.
var quiz_questions = [
    {
        "category": "Entertainment: Video Games",
        "type": "multiple",
        "difficulty": "medium",
        "question": "What is the main character of Metal Gear Solid 2?",
        "correct_answer": "Raiden",
        "answers": [
            "Raiden",
            "Solidus Snake",
            "Big Boss",
            "Venom Snake"
        ]
    },
    {
        "category": "Science & Nature",
        "type": "multiple",
        "difficulty": "easy",
        "question": "What is the hottest planet in the Solar System?",
        "correct_answer": "Venus",
        "answers": [
            "Venus",
            "Mars",
            "Mercury",
            "Jupiter"
        ]
    },
    {
        "category": "Entertainment: Books",
        "type": "multiple",
        "difficulty": "hard",
        "question": "What is Ron Weasley's middle name?",
        "correct_answer": "Bilius",
        "answers": [
            "Bilius",
            "Arthur",
            "John",
            "Dominic"
        ]
    },
    {
        "category": "Entertainment: Music",
        "type": "boolean",
        "difficulty": "medium",
        "question": "Ashley Frangipane performs under the stage name Halsey.",
        "correct_answer": "True",
        "answers": [
            "True",
            "False"
        ]
    },
    {
        "category": "History",
        "type": "multiple",
        "difficulty": "medium",
        "question": "The Herero genocide was perpetrated in Africa by which of the following colonial nations?",
        "correct_answer": "Germany",
        "answers": [
            "Germany",
            "Britain",
            "Belgium",
            "France"
        ]
    }
]

export default {
    //name of the component
    name: 'app',
    //function that returns data to the components
    data() {
        return {
            //question index, used to show the current question
            questionindex: 0,
            //set the variable quizez to the questions defined earlier
            quizez: quiz_questions,
            //create an array of the length of the questions, and assign them to an empty value.
            answers: Array(quiz_questions.length).fill(''),
        }
    },
    computed: {
        score() {
            var total = 0;
            for (var i = 0; i < this.answers.length; i++) {
                if (this.answers[i] == this.quizez[i].correct_answer) {
                    total += 1;
                }
            }
            return total;
        }
    }
}
</script>

<style>
#app {
    font-family: 'Avenir', Helvetica, Arial, sans-serif;
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
    text-align: center;
    color: #2c3e50;
    margin-top: 60px;
}
</style>
Packaging Electron To Use The Production Ready App

Right now, the application still runs from the development server. It is now time to run the app from the file directly, to be packaged with Electron.

On the terminal running the Vue server, hit ctrl+c, then run the following command:

npm run build

After running this, a file would be created in your root folder, under dist/index.html. Open up the file, remove all leading / from all references to JS or CSS files, then close. If we don't do this, our application would load only an empty screen, as it would not be able to locate our CSS and JavaScript files.

At this point, let's go back into our elect.js, and add some configurations to make it serve from the file. At the top of the file, add these two imports:

const url = require('url')
const path = require('path')

Lets replace the part that says win.loadURL('http://localhost:8080') with the code below:

win.loadURL(url.format({
    pathname: path.join(__dirname, 'dist/index.html'),
    protocol: 'file:',
    slashes: true
}));

What we have done here is to tell Electron to load the index.html in our dist folder, and it should attempt to load it as a file rather than an actual url.

Once done, save and hit electron .

At this point, we have our app running as seen below:


最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 225,337评论 6 524
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 96,560评论 3 406
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 172,632评论 0 370
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 61,219评论 1 303
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 70,219评论 6 401
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 53,670评论 1 316
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 42,018评论 3 431
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 41,000评论 0 280
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 47,552评论 1 326
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 39,565评论 3 347
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 41,692评论 1 355
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 37,280评论 5 351
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 43,009评论 3 341
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 33,435评论 0 25
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 34,587评论 1 277
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 50,276评论 3 383
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 46,752评论 2 367

推荐阅读更多精彩内容

  • 前日,跟朋友聊天,她说发现你和他说话简直是一模一样,从语气到习惯词,细想之下才发现好像还的确是这样。平日里倒也没有...
    lilythedog阅读 744评论 0 1
  • iOS-KVC和KVO精炼讲解(干货)KVC 和 KVOiOS开发系列--Objective-C之KVC、KVO细...
    sellse阅读 156评论 0 0
  • URL是因特网资源的标准化名称,URI是通用的资源标识符,URL是URI的子集,URL分三部分组成,比如我们访问一...
    咖啡少年不加糖whm阅读 1,159评论 0 1
  • 写一个自定义的tableviewcell 用xib写的约束 首先写了imageview的约束 对上 左 下 个间隔...
    葵安i阅读 268评论 0 0