1. การเชื่อมต่อกับ API
Vue.js ใช้ fetch
หรือไลบรารีอย่าง Axios เพื่อเชื่อมต่อกับ API สำหรับดึงข้อมูลและส่งคำขอไปยัง Backend
การติดตั้ง Axios
1 | npm install axios |
ตัวอย่างการใช้งาน Axios:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | 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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | // 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 หลัก:
1 2 3 4 5 6 7 8 9 10 | import { createStore } from 'vuex'; import posts from './modules/posts'; const store = createStore({ modules: { posts } }); export default store; |
การใช้งานใน Component:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | <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 ช่วยให้ผู้ใช้รับรู้ถึงสถานะของแอปพลิเคชัน
ตัวอย่าง:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | <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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | 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:
1 | npm install @apollo/client graphql |
ตัวอย่างการตั้งค่า Apollo:
1 2 3 4 5 6 7 8 | import { ApolloClient, InMemoryCache } from '@apollo/client'; const apolloClient = new ApolloClient({ uri: 'https://api.example.com/graphql', cache: new InMemoryCache() }); export default apolloClient; |
การใช้งานใน Component:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | <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!