使用 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:


最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • 前日,跟朋友聊天,她說發現你和他說話簡直是一模一樣,從語氣到習慣詞,細想之下才發現好像還的確是這樣。平日里倒也沒有...
    lilythedog閱讀 747評論 0 1
  • iOS-KVC和KVO精煉講解(干貨)KVC 和 KVOiOS開發系列--Objective-C之KVC、KVO細...
    sellse閱讀 157評論 0 0
  • URL是因特網資源的標準化名稱,URI是通用的資源標識符,URL是URI的子集,URL分三部分組成,比如我們訪問一...
    咖啡少年不加糖whm閱讀 1,168評論 0 1
  • 寫一個自定義的tableviewcell 用xib寫的約束 首先寫了imageview的約束 對上 左 下 個間隔...
    葵安i閱讀 284評論 0 0