Given the syntax, I’m assuming you’re using Bootstrap 5.
You’d be better off creating a component Vue component for the product details modal that you can pass a product to as a prop, and then it’ll change its content based on the product.
If you have a list of products that you’re iterating over, then you can do something like this:
<!-- ProductList.vue -->
<template>
<ul>
<li v-for="product in products" v-bind:key="product.id">
<span>{{ product.name }}</span>
<button v-on:click="showDetails(product)">Details</button>
</li>
</ul>
<portal to="modals" v-if="showModal">
<product-details-modal
v-bind:product="product"
v-bind:show="showModal"
v-on: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() {
// Load products from API or something
// Save array of product results to this.products
},
};
</script>
Now when you click the details button, it’ll set the selected product as a data
item, as well as showModal
true. The product is then passed to the modal component, which can show the details based on that prop:
<!-- 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>