In post video, you will learn how to read or get Data from another website using Laravel API and Vuejs (Axios). The following are the steps for getting data from another website and show on your website. Data Format we will receive from another Website is JSON Format.
- First set up Basic Vuejs in your project .for that watch this post. Click here
- we will use Axios for getting data dynamically that’s mean without loading your page .for that we need to install Axios using following line
1npm run --save axios - In resources/js/components/ExampleComponent.vue
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172<template><div class="container"><div class="row justify-content-center"><div class="col-md-8"><div class="card"><div class="card-header">Example Component</div><div class="card-body">hellow welcome to vuejs world</div></div><br><br><br><br><div class="card postclss" v-for="pdata in posts" ><div class="card-header"> <h3 style="color: brown">{{ pdata.title }}</h3></div><div class="card-body"><p>{{ pdata.body }}</p></div><br><br></div><br><br></div></div></div></template><script>import axios from 'axios'export default {data(){return {posts:[]}},mounted() {var self=this;console.log('Component mounted.')console.log("axios data")axios.get('https://jsonplaceholder.typicode.com/posts').then(function(res){self.posts=res.data;console.log("Data from another website: ",res.data)}).catch(function(error){console.log("Errors ",error);})}}</script><style>.post{background: green;margin-bottom: 30px;padding: 15px 25px;}</style>
what’s happening here <script> import axios from ‘axios’ here we are importing axios package as axios and then when the component is rendered mounted() will be called.Inside mounted() function, via axios.get() we are getting the API data which we will display on our site. if you see in the browser https://jsonplaceholder.typicode.com/posts you will find the following type JSON data.When the data will be rendered successfully .then() function will be called , otherwise if failed to load then catch() function will be called.
- run following in theĀ Terminal
1npm run watch
Finally, on the browser, you will find your desire data. You may face CORS Problem, here is the link for the solution.