본문으로 건너뛰기

เนื้อหาภาษาไทย / 태국어 콘텐츠

시스템 가이드 검수 완료된 콘텐츠

การทำงานร่วมกันกับ API และ Backend อย่างมีประสิทธิภาพ

Vue.js ใช้ fetch หรือไลบรารีอย่าง Axios เพื่อเชื่อมต่อกับ API สำหรับดึงข้อมูลและส่งคำขอไปยัง Backend

1. การเชื่อมต่อกับ API

Vue.js ใช้ fetch หรือไลบรารีอย่าง Axios เพื่อเชื่อมต่อกับ API สำหรับดึงข้อมูลและส่งคำขอไปยัง Backend

การติดตั้ง Axios

npm install axios

ตัวอย่างการใช้งาน Axios:

import axios from 'axios';

export default {
  data() {
    return {
      posts: []
    };
  },
  methods: {
    async fetchPosts() {
      try {
        const response = await axios.get('https://jsonplaceholder.typicode.com/posts');
        this.posts = response.data;
      } catch (error) {
        console.error('Error fetching posts:', error);
      }
    }
  },
  mounted() {
    this.fetchPosts();
  }
};

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

เมื่อแอปพลิเคชันของคุณต้องการจัดการข้อมูลที่มาจาก API การใช้ Vuex เพื่อจัดการ State จะช่วยเพิ่มความยืดหยุ่นและความสามารถในการ Reuse

การตั้งค่า Vuex สำหรับจัดการ API:

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

const state = {
  posts: []
};

const mutations = {
  SET_POSTS(state, posts) {
    state.posts = posts;
  }
};

const actions = {
  async fetchPosts({ commit }) {
    try {
      const response = await axios.get('https://jsonplaceholder.typicode.com/posts');
      commit('SET_POSTS', response.data);
    } catch (error) {
      console.error('Error fetching posts:', error);
    }
  }
};

const getters = {
  allPosts: (state) => state.posts
};

export default {
  state,
  mutations,
  actions,
  getters
};

การเพิ่ม Module นี้ใน Store หลัก:

import { createStore } from 'vuex';
import posts from './modules/posts';

const store = createStore({
  modules: {
    posts
  }
});

export default store;

การใช้งานใน Component:

<template>
  <div>
    <h1>Posts</h1>
    <ul>
      <li v-for="post in posts" :key="post.id">{{ post.title }}</li>
    </ul>
  </div>
</template>

<script>
import { mapGetters, mapActions } from 'vuex';

export default {
  computed: {
    ...mapGetters(['allPosts'])
  },
  methods: {
    ...mapActions(['fetchPosts'])
  },
  mounted() {
    this.fetchPosts();
  }
};
</script>

3. การจัดการ Errors และ Loading State

การจัดการ Errors และการแสดง Loading State ช่วยให้ผู้ใช้รับรู้ถึงสถานะของแอปพลิเคชัน

ตัวอย่าง:

<template>
  <div>
    <p v-if="loading">Loading...</p>
    <p v-if="error" style="color: red">Error: {{ error }}</p>
    <ul v-else>
      <li v-for="post in posts" :key="post.id">{{ post.title }}</li>
    </ul>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      posts: [],
      loading: true,
      error: null
    };
  },
  methods: {
    async fetchPosts() {
      this.loading = true;
      this.error = null;
      try {
        const response = await axios.get('https://jsonplaceholder.typicode.com/posts');
        this.posts = response.data;
      } catch (err) {
        this.error = 'Failed to fetch posts';
      } finally {
        this.loading = false;
      }
    }
  },
  mounted() {
    this.fetchPosts();
  }
};
</script>

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

สำหรับแอปพลิเคชันที่ต้องการการยืนยันตัวตน คุณสามารถใช้ Axios Interceptors เพื่อจัดการ Token Authentication

การตั้งค่า Axios Interceptor:

import axios from 'axios';

const apiClient = axios.create({
  baseURL: 'https://api.example.com',
  headers: {
    'Content-Type': 'application/json'
  }
});

apiClient.interceptors.request.use((config) => {
  const token = localStorage.getItem('token');
  if (token) {
    config.headers.Authorization = `Bearer ${token}`;
  }
  return config;
});

export default apiClient;

5. การใช้ GraphQL กับ Vue.js

หาก Backend ใช้ GraphQL คุณสามารถใช้ไลบรารี Apollo Client สำหรับ Vue.js

การติดตั้ง Apollo Client:

npm install @apollo/client graphql

ตัวอย่างการตั้งค่า Apollo:

import { ApolloClient, InMemoryCache } from '@apollo/client';

const apolloClient = new ApolloClient({
  uri: 'https://api.example.com/graphql',
  cache: new InMemoryCache()
});

export default apolloClient;

การใช้งานใน Component:

<template>
  <div>
    <h1>Users</h1>
    <ul>
      <li v-for="user in users" :key="user.id">{{ user.name }}</li>
    </ul>
  </div>
</template>

<script>
import { gql } from 'graphql-tag';
import { useQuery } from '@apollo/client';

const GET_USERS = gql`
  query {
    users {
      id
      name
    }
  }
`;

export default {
  setup() {
    const { data } = useQuery(GET_USERS);
    return {
      users: data?.users || []
    };
  }
};
</script>

6. สรุป

ในบทนี้ คุณได้เรียนรู้เกี่ยวกับ:

  • การเชื่อมต่อและการดึงข้อมูลจาก API ด้วย Axios
  • การจัดการ State และ API ผ่าน Vuex
  • การจัดการ Errors และ Loading State
  • การตั้งค่า Token Authentication
  • การใช้งาน GraphQL กับ Apollo Client

ในบทถัดไป เราจะสำรวจเครื่องมือเสริม (Tooling) สำหรับการพัฒนา Vue.js เช่น Vue CLI Plugins และการตั้งค่าด้วย Vite!

Office.in.th Custom Service

이 구조를 바탕으로 시스템을 개발하거나 맞춤 변경하고 싶으신가요?

Office.in.th는 엔터프라이즈 웹 애플리케이션, API 연동, 공공/민간 업무 관리 시스템을 설계·개발하며 장기 지원을 제공합니다.

소프트웨어 개발 서비스 보기