首頁 > web前端 > js教程 > 主體

Node.js與Vue.js怎麼搭建一個全端項目

PHPz
發布: 2023-04-05 14:23:01
原創
893 人瀏覽過

Node.js和Vue.js是目前非常流行的兩個技術,其中Node.js是基於JavaScript運行的伺服器端開發平台,而Vue.js則是用於建立使用者介面的漸進式框架。這兩個技術的結合可以大大提高Web應用的開發效率和使用者體驗。在本文中,我們將透過一個實際的專案來展示如何使用Node.js和Vue.js建立一個全端Web應用程式。

一、專案介紹

我們將開發一個簡單的文章發佈和管理系統,使用者可以透過註冊登入來發布文章、評論以及查看其他使用者發佈的文章。為了實現這項功能,我們將使用Node.js作為後端開發語言和技術框架,使用Vue.js作為前端開發框架,並使用MongoDB作為資料庫。

二、環境搭建

在開始開發之前,首先需要先在本機環境中建立好Node.js、Vue.js和MongoDB的開發環境。

1、安裝Node.js:可以從官網下載Node.js的安裝包進行安裝。

2、安裝Vue.js:可以使用npm命令列工具安裝Vue.js。在命令列中輸入以下命令:

npm install -g vue-cli
登入後複製

3、安裝MongoDB:可以從官網下載MongoDB的安裝套件並安裝。

三、專案結構

我們將專案分為前端和後端兩個部分,因此需要分別建立兩個資料夾來存放這兩部分的程式碼,我們可以在專案的根目錄下建立一個名為「node-vue-app」的資料夾來存放整個專案。

1、建立後端部分

在「node-vue-app」資料夾​​下建立一個名為「server」的資料夾,在該資料夾下建立一個名為「 app.js」的文件,該文件將作為我們的後端服務入口文件。同時,我們需要在「server」資料夾下建立一個名為「routes」的資料夾,用於存放路由程式碼;並在「server」資料夾下建立一個名為「models」的資料夾,用於存放資料模型代碼。

2、建立前端部分

在「node-vue-app」資料夾​​下建立一個名為「client」的資料夾,我們將在該資料夾下進行前端開發。可以使用Vue.js提供的命令列工具建立一個Vue.js專案:

vue init webpack client
登入後複製

該命令將在「client」資料夾下建立一個名為「src」的資料夾,該資料夾將包含我們的所有前端程式碼。

四、後端開發

在本案例中,我們將使用Express作為後端框架來完成RESTful API的開發。在「app.js」檔案中,我們需要引入相關模組和函式庫,並初始化Express應用程式:

const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');

const app = express();
app.use(bodyParser.json());

mongoose.connect('mongodb://localhost:27017/node-vue-app', { useNewUrlParser: true });
mongoose.connection.once('open', () => {
    console.log('connected to database');
});

app.listen(3000, () => console.log('server is running on port 3000'));
登入後複製

1、定義資料模型

我們需要在「models」資料夾下定義我們的資料模型,建立一個名為「article.js」的檔案:

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const articleSchema = new Schema({
    title: String,
    author: String,
    content: String,
    created_at: Date,
    updated_at: Date
});

module.exports = mongoose.model('Article', articleSchema);
登入後複製

在該檔案中,我們定義了一個名為「Article」的資料模型,並定義了對應的資料結構。

2、定義路由

在「routes」資料夾下建立一個名為「articles.js」的文件,我們將在該文件中定義文章相關的路由處理邏輯:

const express = require('express');
const router = express.Router();
const Article = require('../models/article');

// 获取文章列表
router.get('/', (req, res) => {
    Article.find((err, articles) => {
        if (err) {
            console.log(err);
        } else {
            res.json({ articles });
        }
    });
});

// 获取单篇文章
router.get('/:id', (req, res) => {
    Article.findById(req.params.id, (err, article) => {
        if (err) {
            console.log(err);
        } else {
            res.json({ article });
        }
    });
});

// 新增文章
router.post('/', (req, res) => {
    const article = new Article(req.body);
    article.save()
        .then(() => res.json({ success: true }))
        .catch(err => console.log(err));
});

// 更新文章
router.put('/:id', (req, res) => {
    Article.findByIdAndUpdate(req.params.id, req.body, { new: true }, (err, article) => {
        if (err) {
            console.log(err);
        } else {
            res.json({ article });
        }
    });
});

// 删除文章
router.delete('/:id', (req, res) => {
    Article.findByIdAndRemove(req.params.id, (err, article) => {
        if (err) {
            console.log(err);
        } else {
            res.json({ article });
        }
    });
});

module.exports = router;
登入後複製

在該檔案中,我們定義了文章相關的所有路由處理邏輯,包括取得文章清單、取得單篇文章、新增文章、更新文章和刪除文章。

五、前端開發

在本案例中,我們將使用Vue.js元件來完成前端開發。在「client/src」資料夾下建立一個名為「components」的資料夾,用於存放Vue.js元件,我們將在該資料夾下建立一個名為「Articles」的元件,該元件將實作文章清單的展示、新增、編輯和刪除:

<template>
    <div class="articles">
        <table>
            <thead>
                <tr>
                    <th>ID</th>
                    <th>Title</th>
                    <th>Author</th>
                    <th>Created At</th>
                    <th>Updated At</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
                <tr v-for="article in articles" :key="article._id">
                    <td>{{ article._id }}</td>
                    <td>{{ article.title }}</td>
                    <td>{{ article.author }}</td>
                    <td>{{ article.created_at }}</td>
                    <td>{{ article.updated_at }}</td>
                    <td>
                        <button @click="edit(article._id)">Edit</button>
                        <button @click="del(article._id)">Delete</button>
                    </td>
                </tr>
            </tbody>
        </table>
        <div class="form">
            <form @submit.prevent="submit">
                <input type="text" v-model="article.title" placeholder="Title">
                <input type="text" v-model="article.author" placeholder="Author">
                <textarea v-model="article.content" placeholder="Content"></textarea>
                <button type="submit">{{ isNew ? 'Create' : 'Update' }}</button>
            </form>
        </div>
    </div>
</template>

<script>
    export default {
        data() {
            return {
                articles: [],
                article: {
                    title: '',
                    author: '',
                    content: ''
                },
                isNew: true
            }
        },
        created() {
            this.getArticles();
        },
        methods: {
            getArticles() {
                fetch('/api/articles')
                    .then(res => res.json())
                    .then(data => this.articles = data.articles)
                    .catch(err => console.log(err));
            },
            createArticle() {
                fetch('/api/articles', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(this.article)
                })
                    .then(res => res.json())
                    .then(data => {
                        if (data.success) {
                            this.article = { title: '', author: '', content: '' };
                            this.getArticles();
                        }
                    })
                    .catch(err => console.log(err));
            },
            updateArticle(id) {
                fetch(`/api/articles/${id}`, {
                    method: 'PUT',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(this.article)
                })
                    .then(res => res.json())
                    .then(data => {
                        if (data.article) {
                            this.article = { title: '', author: '', content: '' };
                            this.isNew = true;
                            this.getArticles();
                        }
                    })
                    .catch(err => console.log(err));
            },
            deleteArticle(id) {
                fetch(`/api/articles/${id}`, {
                    method: 'DELETE'
                })
                    .then(res => res.json())
                    .then(data => {
                        if (data.article) {
                            this.getArticles();
                        }
                    })
                    .catch(err => console.log(err));
            },
            submit() {
                if (this.isNew) {
                    this.createArticle();
                } else {
                    this.updateArticle(this.article._id);
                }
            },
            edit(id) {
                const article = this.articles.find(a => a._id === id);
                this.article = { ...article };
                this.isNew = false;
            },
            del(id) {
                const article = this.articles.find(a => a._id === id);
                if (window.confirm(`Are you sure to delete article: ${article.title}?`)) {
                    this.deleteArticle(id);
                }
            }
        }
    }
</script>

<style scoped>
    table {
        border-collapse: collapse;
        width: 100%;
    }
    td, th {
        border: 1px solid #ddd;
        padding: 8px;
        text-align: left;
    }
    tr:nth-child(even) {
        background-color: #f2f2f2;
    }
    form {
        display: flex;
        flex-direction: column;
    }
    textarea {
        height: 100px;
    }
    button {
        margin-top: 10px;
        padding: 8px 16px;
        background-color: #1E6FAF;
        color: #fff;
        border: none;
        border-radius: 4px;
        cursor: pointer;
    }
    button:hover {
        background-color: #15446F;
    }
</style>
登入後複製

在該元件中,我們定義了一個名為「Articles」的Vue.js元件,並實作了文章清單的展示、新增、編輯和刪除功能,該元件呼叫了後端API,透過fetch()函數來取得、建立、更新和刪除文章。

六、啟動應用程式

在完成了後端和前端開發之後,我們需要啟動應用程式來驗證我們的程式碼是否正常運作。在命令列中進入專案根目錄,並分別在「server」和「client」資料夾下執行以下命令:

npm install
npm start
登入後複製

此指令將分別啟動後端和前端服務,並在瀏覽器中開啟前端應用程式。在瀏覽器中輸入「http://localhost:8080」即可存取我們的文章發佈和管理系統。

七、總結

Node.js和Vue.js的結合可以幫助我們快速建立一個全端Web應用,並且可以實現高效的開發和良好的使用者體驗。在本文中,我們透過一個實際的專案展示如何使用Node.js和Vue.js建立一個全端Web應用,相信本文可以幫助各位開發者更能理解Node.js和Vue.js的應用。

以上是Node.js與Vue.js怎麼搭建一個全端項目的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!