前端Web前端之路Vue.js开发技巧

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

2017-05-22  本文已影响968人  与蟒唯舞

随着 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:


上一篇下一篇

猜你喜欢

热点阅读