跳到主要内容

เนื้อหาภาษาไทย / 泰语内容

系统指南 内容已审核

การรวม Vue.js กับระบบ Backend เพื่อพัฒนา Full Stack Application

Full Stack Application หมายถึงแอปพลิเคชันที่รวมส่วน Frontend (เช่น Vue.js) และ Backend (เช่น Node.js, Django, หรือ Laravel) เข้าด้วยกัน โดย Backend ทำหน้าที่จัด...

1. Full Stack Application คืออะไร?

Full Stack Application หมายถึงแอปพลิเคชันที่รวมส่วน Frontend (เช่น Vue.js) และ Backend (เช่น Node.js, Django, หรือ Laravel) เข้าด้วยกัน โดย Backend ทำหน้าที่จัดการข้อมูลและธุรกิจลอจิก ในขณะที่ Frontend แสดงผลและโต้ตอบกับผู้ใช้


2. การตั้งค่าระบบ Backend สำหรับการทำงานร่วมกับ Vue.js

ตัวอย่างการใช้ Node.js และ Express

Express.js เป็น Framework สำหรับสร้าง REST API ที่ได้รับความนิยมใน Node.js

การติดตั้ง Express:

npm install express cors body-parser

ตัวอย่างเซิร์ฟเวอร์ Express:

// server.js
const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');

const app = express();
const port = 3000;

app.use(cors());
app.use(bodyParser.json());

let items = [
  { id: 1, name: 'Item 1' },
  { id: 2, name: 'Item 2' }
];

app.get('/api/items', (req, res) => {
  res.json(items);
});

app.post('/api/items', (req, res) => {
  const newItem = req.body;
  items.push(newItem);
  res.status(201).json(newItem);
});

app.listen(port, () => {
  console.log(`Server is running at http://localhost:${port}`);
});

3. การเชื่อมต่อ Vue.js กับ API

การติดตั้ง Axios สำหรับการทำงานกับ API:

npm install axios

การดึงข้อมูลจาก API:

<template>
  <div>
    <h1>Items</h1>
    <ul>
      <li v-for="item in items" :key="item.id">{{ item.name }}</li>
    </ul>
    <input v-model="newItem" placeholder="Add new item" />
    <button @click="addItem">Add Item</button>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      items: [],
      newItem: ''
    };
  },
  methods: {
    async fetchItems() {
      const response = await axios.get('http://localhost:3000/api/items');
      this.items = response.data;
    },
    async addItem() {
      const newItem = { id: Date.now(), name: this.newItem };
      await axios.post('http://localhost:3000/api/items', newItem);
      this.items.push(newItem);
      this.newItem = '';
    }
  },
  mounted() {
    this.fetchItems();
  }
};
</script>

4. การจัดการ Authentication

การเพิ่ม Token Authentication

การใช้ Token Authentication ช่วยให้การยืนยันตัวตนระหว่าง Frontend และ Backend มีความปลอดภัย

การเพิ่ม JWT (JSON Web Token) ใน Backend:

npm install jsonwebtoken
const jwt = require('jsonwebtoken');
const secretKey = 'mySecretKey';

app.post('/api/login', (req, res) => {
  const { username, password } = req.body;
  if (username === 'admin' && password === 'password') {
    const token = jwt.sign({ username }, secretKey, { expiresIn: '1h' });
    res.json({ token });
  } else {
    res.status(401).json({ message: 'Invalid credentials' });
  }
});

app.get('/api/protected', (req, res) => {
  const token = req.headers.authorization.split(' ')[1];
  jwt.verify(token, secretKey, (err, decoded) => {
    if (err) {
      res.status(401).json({ message: 'Unauthorized' });
    } else {
      res.json({ message: 'Welcome to protected route!', user: decoded });
    }
  });
});

การส่ง Token จาก Vue.js:

<script>
import axios from 'axios';

export default {
  data() {
    return {
      username: '',
      password: '',
      token: ''
    };
  },
  methods: {
    async login() {
      const response = await axios.post('http://localhost:3000/api/login', {
        username: this.username,
        password: this.password
      });
      this.token = response.data.token;
      axios.defaults.headers.common['Authorization'] = `Bearer ${this.token}`;
    },
    async accessProtectedRoute() {
      const response = await axios.get('http://localhost:3000/api/protected');
      console.log(response.data);
    }
  }
};
</script>

5. การจัดการ State ด้วย Vuex

การใช้ Vuex ช่วยให้การจัดการข้อมูลจาก API เป็นระบบและง่ายต่อการบำรุงรักษา

ตัวอย่าง Vuex Store:

// store/modules/items.js
import axios from 'axios';

export default {
  state: {
    items: []
  },
  mutations: {
    SET_ITEMS(state, items) {
      state.items = items;
    },
    ADD_ITEM(state, item) {
      state.items.push(item);
    }
  },
  actions: {
    async fetchItems({ commit }) {
      const response = await axios.get('http://localhost:3000/api/items');
      commit('SET_ITEMS', response.data);
    },
    async addItem({ commit }, item) {
      await axios.post('http://localhost:3000/api/items', item);
      commit('ADD_ITEM', item);
    }
  },
  getters: {
    allItems: (state) => state.items
  }
};

6. สรุป

ในบทนี้ คุณได้เรียนรู้วิธีรวม Vue.js เข้ากับระบบ Backend เพื่อพัฒนา Full Stack Application รวมถึงการสร้าง REST API, การเชื่อมต่อกับ API ด้วย Axios, การจัดการ Authentication ด้วย JWT, และการจัดการ State ด้วย Vuex

ในบทถัดไป เราจะศึกษาเกี่ยวกับการพัฒนาแอปพลิเคชันที่มีประสิทธิภาพและการจัดการโครงสร้างโปรเจกต์ใน Vue.js!

Office.in.th Custom Service

想基于此结构开发或定制系统?

Office.in.th 承接企业级 Web Application、API Integration 以及政府/企业管理系统的设计与开发,并提供长期支持。

查看软件开发服务