Home > Back-end >  how to send click button's value to a props
how to send click button's value to a props

Time:08-24

In my parent component I have a button and child component:

<div> @click="editMe(edit)" />
     <edit-team :openModal="openModal"/>
</div>

export default {

  data() {
    return {
      openModal: false,
    };
  },
  method: {
      editMe(edit) {
      this.openModal = true;
    },
  }
}

So after I click the editMe button, I am expecting openModal becomes true and goes true to child component.

<template>
  <el-dialog
    :visible.sync="modal"
  />
</template>

<script>
export default {
  props: {
    openModal: {
      type: Boolean,
      required: true,
    },
  },

  data() {
    return {
      modal: this.openModal,
    };
  },
</script>

But unfortunately, the modal is not opening because props comes as false always. I assigned openModal to new variable because it was giving me a warning about mutating props. So how do you think I can send the props in right value?

CodePudding user response:

In child just try this

<template>
  <el-dialog
    :visible.sync="openModal"
  />
</template>

<script>
export default {
  props: {
    openModal: {
      type: Boolean,
      required: true,
    },
  },
  },
</script>

CodePudding user response:

If you have sibilngs components and you need to retrieve data, you can use the emit keyword and emit events

Then it will work like this :

  • The sibling emit the event to show the modal
  • The parent update the showModalData to true
  • This child is re-rendered

Vue.component('modal', {
  template: '#modal',
  props: ['show'],
});


Vue.component('buttonModal', {
  template: '#buttonModal',
  methods: {
    showModal(){
      this.$emit('show-modal-button', true)
    }
  }
});

new Vue({
  el: '#app',
  data: () => ({
    showModalData: false
  }),

  methods: {
    editMe() {
      this.showModalData = true
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.13/vue.js"></script>

<div id="app">
  <p>this is the parent</p>
  
  <hr>
  
  <button-modal @show-modal-button="editMe">Show modal</button-modal>
  
  <hr>
  <modal :show="showModalData" />
</div>

<template id="modal">
  <div>
  props show : {{ show }}
  <h2 v-if="show">This is the modal</h2>    
  </div>
</template>


<template id="buttonModal">
<div>
    <p>This is the sibilng</p>
    <button @click="showModal"> Show the modal through sibiling components </button>
  </div>
</template>

  • Related