使用 Vue.js 2 + Electron 開(kāi)發(fā)桌面應(yīng)用

隨著 JavaScript 開(kāi)源社區(qū)的發(fā)展烂瘫,JavaScript 的應(yīng)用場(chǎng)景越來(lái)越廣泛媒熊,到目前為止奇适,JavaScript 在Web開(kāi)發(fā)、桌面開(kāi)發(fā)芦鳍、APP開(kāi)發(fā)嚷往、服務(wù)端開(kāi)發(fā)方面都可以勝任。

在桌面開(kāi)發(fā)方面柠衅,如果你熟悉 CFと剩或 Java 等技術(shù),你就知道構(gòu)建桌面應(yīng)用程序的復(fù)雜菲宴,有時(shí)可能需要自己編寫 DLL(動(dòng)態(tài)鏈接庫(kù))文件贷祈。而 Electron 則基于 HTML、CSS喝峦、JavaScript势誊,并且是跨平臺(tái)的。目前有很多優(yōu)秀的桌面軟件都是使用 Electron 開(kāi)發(fā)的:

微軟的 VSCode 也是基于 Electron 開(kāi)發(fā)的谣蠢,居然沒(méi)用自己的開(kāi)發(fā)套件粟耻,可見(jiàn) Electron 的桌面解決方案的優(yōu)秀。

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:


最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子们拙,更是在濱河造成了極大的恐慌,老刑警劉巖嚼贡,帶你破解...
    沈念sama閱讀 216,470評(píng)論 6 501
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡,警方通過(guò)查閱死者的電腦和手機(jī)赏僧,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,393評(píng)論 3 392
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)谈宛,“玉大人次哈,你說(shuō)我怎么就攤上這事胎署∵郝迹” “怎么了?”我有些...
    開(kāi)封第一講書人閱讀 162,577評(píng)論 0 353
  • 文/不壞的土叔 我叫張陵琼牧,是天一觀的道長(zhǎng)恢筝。 經(jīng)常有香客問(wèn)我,道長(zhǎng)巨坊,這世上最難降的妖魔是什么撬槽? 我笑而不...
    開(kāi)封第一講書人閱讀 58,176評(píng)論 1 292
  • 正文 為了忘掉前任,我火速辦了婚禮趾撵,結(jié)果婚禮上侄柔,老公的妹妹穿的比我還像新娘共啃。我一直安慰自己,他們只是感情好暂题,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,189評(píng)論 6 388
  • 文/花漫 我一把揭開(kāi)白布移剪。 她就那樣靜靜地躺著,像睡著了一般薪者。 火紅的嫁衣襯著肌膚如雪纵苛。 梳的紋絲不亂的頭發(fā)上,一...
    開(kāi)封第一講書人閱讀 51,155評(píng)論 1 299
  • 那天言津,我揣著相機(jī)與錄音攻人,去河邊找鬼。 笑死悬槽,一個(gè)胖子當(dāng)著我的面吹牛怀吻,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播陷谱,決...
    沈念sama閱讀 40,041評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼烙博,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來(lái)了烟逊?” 一聲冷哼從身側(cè)響起渣窜,我...
    開(kāi)封第一講書人閱讀 38,903評(píng)論 0 274
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎宪躯,沒(méi)想到半個(gè)月后乔宿,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,319評(píng)論 1 310
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡访雪,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,539評(píng)論 2 332
  • 正文 我和宋清朗相戀三年详瑞,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片臣缀。...
    茶點(diǎn)故事閱讀 39,703評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡坝橡,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出精置,到底是詐尸還是另有隱情计寇,我是刑警寧澤,帶...
    沈念sama閱讀 35,417評(píng)論 5 343
  • 正文 年R本政府宣布脂倦,位于F島的核電站番宁,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏赖阻。R本人自食惡果不足惜蝶押,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,013評(píng)論 3 325
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望火欧。 院中可真熱鬧棋电,春花似錦茎截、人聲如沸。這莊子的主人今日做“春日...
    開(kāi)封第一講書人閱讀 31,664評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至招刨,卻和暖如春霎俩,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背沉眶。 一陣腳步聲響...
    開(kāi)封第一講書人閱讀 32,818評(píng)論 1 269
  • 我被黑心中介騙來(lái)泰國(guó)打工打却, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人谎倔。 一個(gè)月前我還...
    沈念sama閱讀 47,711評(píng)論 2 368
  • 正文 我出身青樓柳击,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親片习。 傳聞我的和親對(duì)象是個(gè)殘疾皇子捌肴,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,601評(píng)論 2 353

推薦閱讀更多精彩內(nèi)容

  • 前日状知,跟朋友聊天,她說(shuō)發(fā)現(xiàn)你和他說(shuō)話簡(jiǎn)直是一模一樣孽查,從語(yǔ)氣到習(xí)慣詞饥悴,細(xì)想之下才發(fā)現(xiàn)好像還的確是這樣。平日里倒也沒(méi)有...
    lilythedog閱讀 741評(píng)論 0 1
  • iOS-KVC和KVO精煉講解(干貨)KVC 和 KVOiOS開(kāi)發(fā)系列--Objective-C之KVC盲再、KVO細(xì)...
    sellse閱讀 156評(píng)論 0 0
  • URL是因特網(wǎng)資源的標(biāo)準(zhǔn)化名稱西设,URI是通用的資源標(biāo)識(shí)符,URL是URI的子集答朋,URL分三部分組成贷揽,比如我們?cè)L問(wèn)一...
    咖啡少年不加糖whm閱讀 1,155評(píng)論 0 1
  • 寫一個(gè)自定義的tableviewcell 用xib寫的約束 首先寫了imageview的約束 對(duì)上 左 下 個(gè)間隔...
    葵安i閱讀 265評(píng)論 0 0