Home > OS >  How can I emit event in a tag inside the component vue.js
How can I emit event in a tag inside the component vue.js

Time:10-12

main.js

Vue.component("modal",{
  
  template : /*html*/`
  <div class="modal is-active" >
    <div class="modal-background"></div>
      <div class="modal-card">
        <header class="modal-card-head">
          <p class="modal-card-title">
            <slot name="header"></slot>
          </p>
          <button class="delete" aria-label="close" @click="$emit('close')"></button>
        </header>
    <section class="modal-card-body">
      <slot></slot>
    </section>
    <footer class="modal-card-foot">
     <slot name="footer">
     </slot>
    </footer>
  </div>  
</div>

  `
});

new Vue({
    el:'#root',

    data : {
        isActive : false
    },
});

index.html

 <modal v-if="isActive"  @close =" isActive = false">
            <template slot="header"> Title</template>
             some thing...
            <div slot="footer"> 
                <button class="button is-success">Save changes</button>
                <button class="button" @close="isActive = false">Cancel</button>
            </div>
        </modal>

The button inside the component is working fine the problem is with the other button outside. So too simply i want this button "inside the modal" <button class="button" @close="isActive = false">Cancel</button> to close the modal that is it :) thanks !

CodePudding user response:

You can listen on event @close only on component like you did here <modal v-if="isActive" @close="isActive=false">. At button inside component you can use @click="isActive=false"

Vue.component("modal",{
  template : `
  <div class="modal is-active" >
    <div class="modal-background"></div>
      <div class="modal-card">
        <header class="modal-card-head">
          <p class="modal-card-title">
            <slot name="header"></slot>
          </p>
          <button class="delete" aria-label="close" @click="$emit('close')"></button>
        </header>
    <section class="modal-card-body">
      <slot></slot>
    </section>
    <footer class="modal-card-foot">
     <slot name="footer">
     </slot>
    </footer>
  </div>  
</div>`
});

new Vue({
  el:'#root',
  data : {
    isActive : false
  },
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="root"> 
  <button @click="isActive = true">open</button>
  <modal v-if="isActive"  @close="isActive = false">
    <template slot="header"> Title</template>
     some thing...
    <div slot="footer"> 
        <button class="button is-success">Save changes</button>
        <button class="button" @click="isActive = false">Cancel</button>
    </div>
  </modal>
</div>

  • Related