Integrating Vue.
js into your PHP-based car rental application will allow you to create a more dynamic,
responsive, and modern user interface. Here’s a step-by-step guide to incorporating Vue.js for key parts
of the application:
### 1. **Set Up Vue.js in Your Application**
To start using Vue.js, you can either include it directly via a CDN or set up a more complex build process
with tools like Webpack or Vue CLI. For simplicity, we’ll use the CDN method.
#### 1.1 **Add Vue.js to Your HTML Template**
Include Vue.js in your `header.php` or directly in specific pages where you want to use it.
```php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Car Rentals</title>
<script src="https://cdn.jsdelivr.net/npm/vue@2"></script>
<link rel="stylesheet" href="path/to/your/css">
</head>
<body>
<!-- Your existing header and navigation -->
<!-- Vue.js app will be mounted here -->
<div id="app">
<!-- Vue components will go here -->
</div>
```
### 2. **Convert Existing Components to Vue.js**
You can progressively enhance your app by converting specific parts to Vue.js.
#### 2.1 **Reservation Form with Vue.js**
We’ll create a Vue.js component for the reservation form to dynamically update the price as the user
selects different options.
**reserve.php**
```php
<?php
include 'header.php';
include 'db.php';
// Fetch car details from the database (for dropdown)
$cars = $conn->query("SELECT id, make, model FROM cars")->fetch_all(MYSQLI_ASSOC);
?>
<div id="app">
<reservation-form :cars='<?php echo json_encode($cars); ?>'></reservation-form>
</div>
<script>
Vue.component('reservation-form', {
props: ['cars'],
data() {
return {
selectedCar: '',
rentalDuration: 1,
season: 'summer',
predictedPrice: null
};
},
methods: {
calculatePrice() {
const vm = this;
fetch(`predict_price.php?car_type=${this.selectedCar}&rental_duration=$
{this.rentalDuration}&season=${this.season}`)
.then(response => response.text())
.then(data => {
vm.predictedPrice = parseFloat(data).toFixed(2);
});
},
watch: {
selectedCar: 'calculatePrice',
rentalDuration: 'calculatePrice',
season: 'calculatePrice'
},
template: `
<div>
<h1>Reserve a Car</h1>
<form action="reserve_car.php" method="post">
<label for="car">Car:</label>
<select v-model="selectedCar" name="car_id" required>
<option v-for="car in cars" :value="car.id">{{ car.make }} {{ car.model }}</option>
</select>
<label for="rental_duration">Rental Duration (days):</label>
<input type="number" v-model="rentalDuration" name="rental_duration" required min="1">
<label for="season">Season:</label>
<select v-model="season" name="season" required>
<option value="summer">Summer</option>
<option value="winter">Winter</option>
<option value="spring">Spring</option>
<option value="fall">Fall</option>
</select>
<p>Predicted Rental Price: ${{ predictedPrice }}</p>
<button type="submit">Reserve</button>
</form>
</div>
});
new Vue({
el: '#app'
});
</script>
<?php $conn->close(); ?>
```
In this example:
- **Vue Component**: `reservation-form` is a Vue component that manages the reservation form.
- **Props**: `cars` are passed from PHP to Vue, making the car data available to Vue.
- **Reactivity**: The form reacts to changes in the selected car, rental duration, and season,
dynamically updating the predicted price.
#### 2.2 **Dynamic Car Listings**
You can use Vue.js to display and filter car listings dynamically.
**car_listings.php**
```php
<?php
include 'header.php';
include 'db.php';
// Fetch all cars from the database
$cars = $conn->query("SELECT id, make, model, daily_rate FROM cars")->fetch_all(MYSQLI_ASSOC);
?>
<div id="app">
<car-listings :cars='<?php echo json_encode($cars); ?>'></car-listings>
</div>
<script>
Vue.component('car-listings', {
props: ['cars'],
data() {
return {
searchQuery: '',
filteredCars: this.cars
};
},
watch: {
searchQuery(newQuery) {
this.filteredCars = this.cars.filter(car =>
car.make.toLowerCase().includes(newQuery.toLowerCase()) ||
car.model.toLowerCase().includes(newQuery.toLowerCase())
);
},
template: `
<div>
<h1>Available Cars</h1>
<input v-model="searchQuery" placeholder="Search for a car...">
<div v-for="car in filteredCars" :key="car.id" class="car-item">
<h2>{{ car.make }} {{ car.model }}</h2>
<p>Daily Rate: ${{ car.daily_rate }}</p>
<a :href="'reserve.php?car_id=' + car.id">Reserve</a>
</div>
</div>
});
new Vue({
el: '#app'
});
</script>
<?php $conn->close(); ?>
```
In this example:
- **Dynamic Filtering**: As users type in the search box, the car listings are filtered in real-time without
reloading the page.
### 3. **Improving the User Interface**
Vue.js is great for enhancing user interaction and creating a smoother experience.
#### 3.1 **Live User Profile Editing**
Let users edit their profile information without page reloads.
**profile.php**
```php
<?php
include 'header.php';
include 'db.php';
// Fetch user profile details from the database
$user_id = $_SESSION['user_id'];
$user = $conn->query("SELECT * FROM users WHERE id = $user_id")->fetch_assoc();
?>
<div id="app">
<user-profile :user='<?php echo json_encode($user); ?>'></user-profile>
</div>
<script>
Vue.component('user-profile', {
props: ['user'],
data() {
return {
editing: false,
formData: { ...this.user }
};
},
methods: {
editProfile() {
this.editing = true;
},
saveProfile() {
const vm = this;
fetch('update_profile.php', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(this.formData)
})
.then(response => response.json())
.then(data => {
if (data.success) {
vm.user = { ...vm.formData };
vm.editing = false;
} else {
alert('Error updating profile');
});
},
template: `
<div>
<h1>User Profile</h1>
<div v-if="!editing">
<p>Name: {{ user.name }}</p>
<p>Email: {{ user.email }}</p>
<button @click="editProfile">Edit</button>
</div>
<div v-else>
<label for="name">Name:</label>
<input v-model="formData.name" type="text" required>
<label for="email">Email:</label>
<input v-model="formData.email" type="email" required>
<button @click="saveProfile">Save</button>
</div>
</div>
});
new Vue({
el: '#app'
});
</script>
<?php $conn->close(); ?>
```
In this example:
- **Editable Form**: Users can edit their profile and save changes directly without a page reload.
- **AJAX Updates**: Profile updates are handled through a `fetch` API call, which sends data to
`update_profile.php`.
**update_profile.php**
```php
<?php
include 'db.php';
$data = json_decode(file_get_contents("php://input"), true);
$user_id = $_SESSION['user_id'];
// Update the user profile in the database
$sql = "UPDATE users SET name = ?, email = ? WHERE id = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("ssi", $data['name'], $data['email'], $user_id);
$response = [];
if ($stmt->execute()) {
$response['success'] = true;
} else {
$response['success'] = false;
echo json_encode($response);
$stmt->close();
$conn->close();
?>
```
### 4. **Advanced Features with Vue.js**
You can implement more advanced features with Vue.js, such as:
- **Vuex**: For state management if your application grows larger.
- **Vue Router**: For client-side routing, making your app feel like a single-page application (SPA).
- **Component Libraries**: Use Vuetify, Element UI, or BootstrapVue to build a visually appealing
interface.
### Conclusion
By integrating Vue.js into your PHP car rental application, you can greatly improve the user experience,
making your app more dynamic,