鉴于语法,我假设您使用的是 Bootstrap 5。
您最好为产品详细信息模式创建一个组件 Vue 组件,您可以将产品作为道具传递给它,然后它将根据产品更改其内容。
如果您有要迭代的产品列表,则可以执行以下操作:
<!-- 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>
现在,当您单击详细信息按钮时,它会将所选产品设置为data
项目,以及showModal
true。然后将产品传递给模态组件,该组件可以根据该道具显示详细信息:
<!-- 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>