1. Chuẩn bị API
- Nếu chưa có link API có thể dùng tạm json-server để làm link API tạm thời
npm install -g json-server
-- Tạo file: ./data/db.json
-- Chạy server data
json-server --watch data/db.json
-- Như vậy là đã tạo được database fake :3
2. Fetching Data với created()
Nên get Data trong hook created()
1 2 3 4 5 6 7 8 |
created() { fetch("http://localhost:3000/user") .then((response) => response.json()) .then((data) => { this.user_list = data; console.log(data); }); }, |
3. Trường hợp dùng setup()
-- Khi dùng setup, có mẫu dùng như sau:
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 |
<template> <div> <u v-if="transactions.length"> <li v-for="(tr, index) in transactions" v-bind:key="index"> {{ tr.name }} - {{ tr.age }} </li> </u> </div> </template> <script> import { ref } from "vue"; export default { //vẫn cần phải nhớ, mọi biến gọi ra trong setup() đều phải được sử dụng, nếu không sẽ lỗi setup() { const transactions = ref([]); const error = ref(null); const fetchData = async () => { try { const response = await fetch("http://localhost:3000/user"); if (!response.ok) throw new Error("Somthing went wrong"); transactions.value = await response.json(); //trả về dạng: [{name:...,age:...}] } catch (e) { error.value = e; console.log(e); } }; fetchData(); return { transactions, error }; }, }; </script> <style scoped> </style> |