从 child 组件 VueJs 添加元素的打开模式

Open modal for add element from child component VueJs

我有一个按钮,可以从 child 打开模式,添加新客户。

如果我在 parent 中有代码,它就可以工作,但我尝试在 child 中实现它。

Parent

<b-button @click="openModal">Add new customer</b-button>
<add-new-customer ref="modal" v-if="addCustomer"></add-new-customer>

openModal() {
   this.$refs.modal.openModalCh()
},

Child

<b-modal
        id="modal-prevent-closing"
        ref="modal"
        title="Add new customer"
        @ok="addCustomer"
>
...code..
</b-modal>
    <add-new-customer ref="modal" v-if="addCustomer" @added="onAddCustomer"></add-new-customer>
    addCustomer() {
       ..code for post a new customer..
    }
    openModal() {
       this.$refs.modal.openModalCh()
    },

您可以通过将 child 作为组件注入 parent 来解决您的问题。并以 props 为例。

您可以将 $attr 绑定到包含从 parent 传递到 child 的所有属性的模态。在本例中,我们将其用作 ID。

通过这种方式,您可以在 parent 中为模态框指定一个 ID,然后使用该 ID 无需引用即可打开模态框。

Parent

<template>
  <div>
      <!-- Use the id that you've given the modal -->
      <b-btn @click="$bvModal.show('add-customer')">Open Modal</b-btn>
      <add-customer-modal id="add-customer" title="add old customer"></add-customer-modal>
  </div>
</template>

<script>
import AddCustomerModal from './components/AddCustomerModal.vue'

export default {
  name: "App",
  components: {
    AddCustomerModal
  }
};
</script>

AddCustomerModal.vue (child)

<template>
  <b-modal
    v-bind="$attrs"
    title="Add new customer"
    @ok="addCustomer"
  ></b-modal>
</template>

<script>
  export default {
    methods: {
      addCustomer() {
        /* Insert logic here */
        console.log('Customer added!')
      }
    }
  }
</script>