每个产品的模式窗口(Vue.js)



我正在开发一个小型在线商店(Vue.js(我有几种不同名称和价格的产品。每个产品都有一个";细节";按钮

我希望当我点击";细节";按钮目前,我总是只显示第一个产品的数据。我不知道如何显示我点击的产品的数据。我大致理解你需要使用";这个";,但到目前为止,还没有解决方案。我在Modal中使用vue-js<slot></slot>

方法:

showModal() {
let myModal = new bootstrap.Modal(
document.getElementById('exampleModal'),
{}
);
myModal.show();
},

我的按钮:

<button @click="showModal">Details</button>

给定语法,我假设您使用的是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项目,以及showModaltrue。然后将产品传递给模态组件,该组件可以显示基于该道具的细节:

<!-- 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>

最新更新