Vue3 Carousel as ES module in Laravel blade template
To use Vue3 Carousel as an ES module in a Laravel Blade template, follow these steps:
- Install Vue3 Carousel: First, you need to install Vue3 Carousel using npm or yarn. Open your terminal and navigate to your Laravel project directory. Run the following command to install Vue3 Carousel:
npm install vue3-carousel@next
or
yarn add vue3-carousel@next
- Register Vue3 Carousel:
Next, you need to register Vue3 Carousel in your Laravel project. Open
resources/js/app.jsfile and add the following line at the end of the file:
import Vue from 'vue'
import { Carousel, Slide, Pagination } from 'vue3-carousel'
Vue.component('vue-carousel', Carousel)
Vue.component('vue-slide', Slide)
Vue.component('vue-pagination', Pagination)
- Create a new component:
Create a new component file named
carousel.vuein theresources/js/componentsdirectory and add the following code:
<template>
<vue-carousel :items-to-show="1" :autoplay="true">
<vue-slide v-for="image in images" :key="image">
<img :src="image" alt="Image">
</vue-slide>
<template #addons>
<vue-pagination></vue-pagination>
</template>
</vue-carousel>
</template>
<script>
export default {
props: {
images: {
type: Array,
required: true
}
}
}
</script>
Replace images with the name of the prop that will receive the array of images.
- Use the component in your Blade template:
Now, you can use the
carousel.vuecomponent in your Blade template. Create a new file namedwelcome.blade.phpin theresources/views/welcome.blade.phpdirectory and add the following code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Welcome</title>
<link href="https://cdn.jsdelivr.net/npm/vue@next/dist/vue.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/vue@next/dist/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vue3-carousel@next/dist/vue3-carousel.esm.browser.min.js"></script>
</head>
<body>
<div id="app">
<carousel :images="images">
<template #default="{ images }">
<div v-for="image in images" :key="image">
<img :src="image" alt="Image">
</div>
</template>
</carousel>
</div>
<script src="./components/carousel.js"></script>
</body>
</html>
Replace images with the name of the prop that will receive the array of images in your component.
- Define the
imagesprop: Finally, define theimagesprop in yourwelcome.blade.phpfile by adding the following code at the beginning of the file:
<?php
$images = [
'image1.jpg',
'image2.jpg',
'image3.jpg'
];
?>
<script>
export default {
data() {
return {
images: <?php echo json_encode($images); ?>
}
}
}
</script>
Replace image1.jpg, image2.jpg, and image3.jpg with the actual paths or URLs of your images.
Now, you should be able to use Vue3 Carousel as an ES module in your Laravel Blade template.