Assuming you are utilizing Bootstrap 5 based on the syntax provided.
It would be beneficial to create a Vue component for the product details modal where you can pass a product as a prop. This way, the content of the modal can dynamically change based on the selected product.
If you are iterating over a list of products, you can implement something similar to the following:
<!-- ProductList.vue -->
<template>
<ul>
<li v-for="product in products" :key="product.id">
<span>{{ product.name }}</span>
<button @click="showDetails(product)">Details</button>
</li>
</ul>
<portal to="modals" v-if="showModal">
<product-details-modal
:product="product"
:show="showModal"
@hide="showModal = false"
/>
</portal>
</template>
<script>
import ProductDetailsModal from './ProductDetailsModal.vue';
export default {
components: {
ProductDetailsModal,
},
data() {
return {
product: null,
products: [],
showModal: false,
};
},
methods: {
showDetails(product) {
this.product = product;
this.showModal = true;
},
},
mounted() {
// Fetch products from API or other source
// Save array of products to this.products
},
};
</script>
When the details button is clicked, the selected product becomes a data
item and sets showModal
to true. The product is then passed to the modal component for displaying the details:
<!-- ProductDetailsModal.vue -->
<template>
<div class="modal fade" id="product-details-modal" ref="modalElement">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="product-details-modal-title">Product Details</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<p>Product name: {{ product.name }}</p>
<p>Product price: {{ product.price }}</p>
</div>
</div>
</div>
</div>
</template>
<script>
import { Modal } from 'bootstrap';
export default {
data() {
return {
modalElement: null,
};
},
mounted() {
this.modalElement = new Modal(this.$refs.modal);
this.modalElement.addEventListener('hide.bs.modal', this.$emit('hide'));
if (this.show) {
this.modalElement.show();
}
},
props: {
product: {
required: true,
type: Object,
},
show: {
default: false,
required: false,
type: Boolean,
},
},
watch: {
show(show) {
if (this.modalElement) {
show ? this.modalElement.show() : this.modalElement.hide();
}
},
},
};
</script>