Introduction:
In modern web development, real-time data loading has become a core feature for many applications. In this article, we will demonstrate how to implement data loading with PHP and Vue.js frameworks. We will provide specific code examples to help you grasp this technique quickly.
Before starting, please make sure you have PHP and Vue.js installed. If not, you can download and install them from their official websites. Additionally, we will create a simple database that contains a "users" table to store user data.
First, create a PHP file named "loadData.php". This file will handle the backend logic to query data from the database and return it to the frontend.
<?php
// Connect to the database
$db = new PDO('mysql:host=localhost;dbname=test', 'root', '');
// Query data
$stmt = $db->query("SELECT * FROM users");
$users = $stmt->fetchAll(PDO::FETCH_ASSOC);
// Return data in JSON format
header('Content-Type: application/json');
echo json_encode($users);
?>
The above code connects to the MySQL database, queries all data from the "users" table, and returns the results as a JSON response to the frontend.
Next, create a Vue instance, using the "mounted" lifecycle hook to call the backend API and load the data.
new Vue({
el: '#app',
data: {
users: [] // Array to store data fetched from the backend
},
mounted() {
this.loadData(); // Call the data loading function when the page loads
},
methods: {
loadData() {
// Use Axios to send an HTTP request
axios.get('loadData.php')
.then(response => {
this.users = response.data;
})
.catch(error => {
console.log(error);
});
}
}
});
In this code, we create a Vue instance and call the "loadData" function within the "mounted" lifecycle hook. This function sends an HTTP request via Axios to the backend "loadData.php" API and assigns the returned data to the "users" array in the Vue instance.
With Vue's "v-for" directive, we can loop through the "users" array and display each user's information in the HTML.
<div id="app">
<ul>
<li v-for="user in users" :key="user.id">
{{ user.name }} - {{ user.email }}
</li>
</ul>
</div>
In the code above, we use the "v-for" directive to iterate over the "users" array and display each user's name and email on the page.
After completing the above steps, open the HTML file in a browser. You should see all the user information loaded from the database. If everything works correctly, the page will display data from the "users" table.
In this article, we learned how to implement data loading with PHP and Vue.js frameworks. The backend PHP file fetches data from the database and returns it in JSON format, while the frontend Vue instance uses Axios to get the data and display it on the page. We hope this article helps you better understand and implement data loading with PHP and Vue.