2

I have a button that should open a modal from a child, that adds a new customer.

It works if I have the code just in parent, but I try to implement this in a 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()
    },

2 Answers 2

1

You can bind $attr to your modal which contains all the attributes passed from the parent to the child. In this case we use it for the ID.

This way you can give the modal an ID in the parent and use that ID to open the modal without a ref.

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>
Sign up to request clarification or add additional context in comments.

1 Comment

It opens, but I get error on @ok="addCustomer" , it doesn't get there. I'm looking now, why.
0

You can solve your problem by injecting your child as a component into your parent. And going through the props for example.

1 Comment

Link not working. I feel the right URL is this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.