Package gọi API
npm install axios
import axios from 'axios';
//getdata
axios.get('https://jsonplaceholder.typicode.com/todos')
.then( response => {
this.TodoData = response.data;
});
}
//get
const response = await axios.delete('/api/delete-task/' + id, {
headers: {
/**
* get token saved from localStorage
*/
Authorization: 'Bearer ' + localStorage.getItem('token'),
}
});
//post
axios.post('/api/create-task',{
name: this.title,
description: this.description,
color: this.color,
token: ''
}, {
headers: {
/**
* get token saved from localStorage
*/
Authorization: 'Bearer ' + localStorage.getItem('token'),
}
})
.then( data => {
/**
* response.data.result
* + true: => create success
* + false: => create fail
*/
if (data.data.result) {
this.title = '';
this.description = '';
this.color = '#ccc';
alert('Thêm thành công');
}
else alert('Thêm không thành công');
});
Không cần phải thêm header vào mỗi khi gọi api, mà chỉ cần thêm vào file js chính là được (thường là app.js hoặc main.js)
axios.interceptors.request.use(req => {
req.headers.authorization = 'Bearer ' + localStorage.getItem('token');
return req;
});
//'Bearer ' + localStorage.getItem('token'): => thay đổi cho phù hợp
https://www.npmjs.com/package/axios
Package tạo mã id không trùng
npm install uuid
import { v4 as uuidv4 } from 'uuid';
//gọi hàm uuidv4 tại nơi muốn sử dụng
addTodo(todo) {
this.TodoData = [...this.TodoData, {id: uuidv4(),title: todo}];
}