首页 > 解决方案 > 如何通过单击另一个 vue 组件中包含的按钮来获取 vue 组件的内容(模态窗口)?

问题描述

我正在尝试将我的基本 Vue 应用程序分类为组件。我有一个产品列表,每个列表都包含一些信息和一个按钮。单击该按钮(更多详细信息按钮)会打开一个模式窗口,其中包含该特定产品的更多信息。我在 Vue 中有一个产品列表组件和一个模态窗口组件。我不确定当用户单击按钮时如何从产品列表中调用包含特定产品信息的模式窗口组件。我将不胜感激。这是我到目前为止所拥有的:

产品列表组件

<template>
    <div class="content">
        <div class="nested" v-for="product in products">
            <div class="one"><span>{{product.Name}}</span></div>
            <div class="two"><img src="src/assets/shape.svg" style="height: 80px; width: 80px;"><span>-{{ product.Reduction_percentage }}%</span></div>       
            <div class="three"><span>{{ product.Short_Description }}</span></div>
            <div class="four"><b-btn v-b-modal="'productModal'" @click="chooseProduct(product)" product_item="'product'">More details</b-btn></div>
        </div>
    </div>
</template>

<script>
export default {
  data () {
    return {
        products: [
              {id: 1, Name: 'Product 1', Reduction_percentage: 30, Short_Description:"Something", Description:"Something more"},
              {id: 2, Name: 'Product 2', Reduction_percentage: 33, Short_Description:"Something", Description:"Something more"},
              {id: 3, Name: 'Product 3', Reduction_percentage: 23, Short_Description:"Something", Description:"Something more"},
              {id: 4, Name: 'Product 4', Reduction_percentage: 77, Short_Description:"Something", Description:"Something more"},
              {id: 5, Name: 'Product 5', Reduction_percentage: 99, Short_Description:"Something", Description:"Something more"},
          ]
    }
  },
methods: {
            chooseProduct: function (product) {
            this.chosenProduct = product
        },
}
</script>

模态窗口组件

<template>
<b-modal id="productModal" v-if="chosenProduct" :title="chosenProduct.Name">
            <div class = "inner-container">
                <div class = "inner-nested">
                    <div class="inner-one"><br> {{chosenProduct.Description}}</div>
                    <div class="inner-two">
                        -{{ chosenProduct.Reduction_percentage }}%</div>  
                    <div class="inner-three"> <button>Buy Now</button></div>
                </div>
            </div>
        </b-modal>
</template>

标签: vue.jsbootstrap-modalvue-component

解决方案


组件通信基本上有 3 类:

  1. 父母对孩子使用道具

  2. 子到父使用发射

  3. Any to any:使用事件总线(不推荐)或将 Vuex添加到您的项目中来处理您的应用程序状态


推荐阅读