Axios paketi api istekleri yapmak için kullanılır.
Projenize axios paketini ekleme;
npm install --save axios vue-axios
Daha sonra app.js dosyasına axios paketini import ediyoruz;
import axios from 'axios' import VueAxios from 'vue-axios' Vue.use(VueAxios, axios)
Örnek bir projede index, create ve dit sayfaları şu şekilde olacaktır;
Örnek Index sayfası axios kullanımı;
<td><router-link :to="{name: 'edit', params: { id: post.id }}" class="btn btn-primary">Edit</router-link></td> <td><button class="btn btn-danger" @click.prevent="deletePost(post.id)">Delete</button></td> ... ... methods: { getPosts() { var uri = 'http://127.0.0.1:8000/api/posts'; this.axios.get(uri).then(response => { this.posts = response.data.data; }); }, deletePost(id) { let uri = `http://127.0.0.1:8000/api/post/delete/${id}`; this.axios.delete(uri).then(response => { let i = this.posts.map(item => item.id).indexOf(id); // find index of your object this.posts.splice(i, 1) }); // this.getPosts(); //let i ile başlayan 2 satırı silinip bu metod çağırabilir, ama fazladan istek atmış oluruz } }
Örnek edit sayfası axios kullanımı
<form @submit.prevent="updatePost"> ... ... created() { let uri = `http://127.0.0.1:8000//api/post/edit/${this.$route.params.id}`; this.axios.get(uri).then((response) => { this.post = response.data; }); }, methods: { updatePost() { let uri = `http://127.0.0.1:8000/api/post/update/${this.$route.params.id}`; this.axios.post(uri, this.post).then((response) => { this.$router.push({name: 'posts'}); }); } }
Örnek create sayfası axios kullanımı
<form @submit.prevent="addPost"> ... ... methods: { addPost(){ let uri = 'http://127.0.0.1:8000/api/post/create'; this.axios.post(uri, this.post) .then((response) => { this.$router.push({name: 'posts'}); }) .catch(error => { this.errors_exist = true; if(error.response.status === 422) { this.errors = error.response.data.errors || {}; } }); } } </script>
İlk Yorumu Siz Yapın