To create a simple dropdown using Vue 3 with the Composition API and integrate it into a Laravel blade file, you can follow these steps:
- Ensure you have Vue 3 installed and configured in your Laravel project.
- Create a new Vue component for the dropdown.
- Use the Composition API within the component to manage the dropdown state.
- Insert the Vue component into your blade file.
- Add an event listener to handle the page load when an option is selected.
Here's a step-by-step solution:
Step 1: Create a Vue Component
Create a new Vue component file named DropdownComponent.vue in your resources/js/components directory.
<template>
<select @change="handleSelection($event)">
<option value="" disabled selected>Select your option</option>
<option value="page1">Page 1</option>
<option value="page2">Page 2</option>
<option value="page3">Page 3</option>
</select>
</template>
<script setup>
import { ref } from 'vue';
const selectedOption = ref('');
const handleSelection = (event) => {
selectedOption.value = event.target.value;
if (selectedOption.value) {
window.location.href = `/${selectedOption.value}`;
}
};
</script>
Step 2: Register the Component
In your resources/js/app.js file, register the component:
import { createApp } from 'vue';
import DropdownComponent from './components/DropdownComponent.vue';
const app = createApp({});
app.component('dropdown-component', DropdownComponent);
app.mount('#app');
Step 3: Use the Component in Blade File
In your blade file, you can now use the Vue component:
<div id="app">
<dropdown-component></dropdown-component>
</div>
Step 4: Compile Your Assets
Run your asset compilation script to compile the Vue component into a JavaScript file that the browser can understand. If you're using Laravel Mix, the command would typically be:
npm run dev
or
npm run watch
for continuous compilation.
Step 5: Include the Compiled JS in Your Blade Layout
Make sure to include the compiled JavaScript file in your blade layout:
<script src="{{ mix('/js/app.js') }}"></script>
Now, when you select an option from the dropdown, the handleSelection method will change the window location to the selected page, effectively loading the new page. Adjust the value attributes of the <option> elements to match the routes of your Laravel application.