vue.js is a JavaScript framework for building user interfaces, function as a web application framework, building advanced single-page applications. Here is a Guide to Use vue.js to Fetch Data From API. We already discussed about Application Programming Interface (API), essentially we fetch data from an API to return data in the JSON format.
Here are official website and Github repository of Vue :
1 | https://vuejs.org/ |
Here is a working example usage of fetching API data with vue.js :
---
1 | https://github.com/sitepoint-editors/vuejs-news |
vue.js : Fetch Data From API
Now, how we will create such application? Axios is an HTTP-client for Ajax requests and frequently used for this kind of purpose :
1 | https://github.com/axios/axios |
We can use Babel JavaScript Preprocessor.
This is a tool for debugging :
1 | https://github.com/vuejs/vue-devtools |
Here is some helpful guides to start with vue.js :
1 | https://vuejs.org/v2/guide/instance.html |
We know that WordPress has RESTful API. So, we can create a web application or Android application with vue.js to show WordPress posts. You can open this URL of our site on browser to test JSON output :
1 | https://thecustomizewindows.com/wp-json/wp/v2/posts/ |
Here is filtered URL for one post last post :
1 | https://thecustomizewindows.com/wp-json/wp/v2/posts/?_embed&per_page=1 |
For Author 1, we can construct the URL in this way :
1 | https://thecustomizewindows.com/wp-json/wp/v2/posts/?_embed&per_page=1&author=1 |
You’ll get WordPress API documentation here :
1 | http://v2.wp-api.org |
We can write a snippet for vue.js in this way, where an ability to show posts from an author is given as option (1 and 2) :
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 | var apiURL = 'https://thecustomizewindows.com/wp-json/wp/v2/posts/?_embed&per_page=1' var posts = new Vue({ el: '#app', data: { authors: ['1', '2'], currentAuthor: '1', posts: null }, created: function() { this.fetchData() }, watch: { currentAuthor: 'fetchData' }, methods: { fetchData: function() { var xhr = new XMLHttpRequest() var self = this xhr.open('GET', apiURL + self.currentAuthor) xhr.onload = function() { self.posts = JSON.parse(xhr.responseText) console.log(self.posts[0].link) } xhr.send() } } }) |
We can add a CSS and HTML (live example on Code Pen, Babel JavaScript Preprocessor, SCSS, vue.js used) :
1 | https://codepen.io/AbhishekGhosh/pen/gvVQzr |
There is actually WordPress theme based on that logic :
1 2 | https://github.com/EvanAgee/vuejs-wordpress-theme-starter https://github.com/rtCamp/VueTheme |
Hope this appears meaningful to the readers to use in real life.
Tagged With paperuri:(7465292d306b7756ddf9fffe8408ec34) , api fetch post vue js , vue js fetch , vue fetch , vuejs fetch , vuejs fetch api , vue fetch api , how fetch api on vue , fetch vuejs , fetch data from api with wordpress