简体   繁体   中英

VueJS 2 - How to Pass Parameters Using $emit

I am working on a modal component using VueJS 2. Right now, it basically works -- I click on a button and the modal opens, etc.

What I want to do now is create a unique name for the modal and associate the button with that particular button.

This is what I have in mind. The modal has a unique name property:

<modal name='myName'>CONTENT</modal>

And this would be the associate button:

<button @click="showModal('myName')"></button>

What I need to figure out is how to pass the parameter of showModal to the modal component.

Here is the method that I'm using in the root vue instance (ie, NOT inside my modal component):

methods: {
    showModal(name) { this.bus.$emit('showModal'); },
}

What I want to do is to access the name property in the component -- something like this:

created() {
    this.bus.$on('showModal', () => alert(this.name));
}

But this shows up as undefined .

So what am I doing wrong? How can I access the name property inside the modal component?

NOTE: If you are wondering what this.bus.$on is, please see the following answer to a previous question that I asked: https://stackoverflow.com/a/42983494/7477670

Pass it as a parameter to $emit .

methods: {
    showModal(name) { this.bus.$emit('showModal', name); },
}

created() {
    this.bus.$on('showModal', (name) => alert(name));
}

Also, if you want to give the modal a name, you need to accept it as a prop in the modal component.

Vue.component("modal",{
    props:["name"],
    ...
})

Then I assume you will want to do something like,

if (name == this.name)
    //show the modal
<!-- File name is dataTable.vue -->
<template>
  <div>
     <insertForm v-on:emitForm="close"></insertForm>
  </div>
</template>


<script>

import InsertForm from "./insertForm";

import Axios from "axios";

export default {
  components: {
    InsertForm
  },

  data: () => ({    
  }),

  methods: {
    
    close(res) {
      console.log('res = ', res);    
    }
  }
};
</script>

<!-- File name is insertForm.vue -->
<template>
  <div>
    <v-btn @click.native="sendPrameter">
      <v-icon>save</v-icon>
    </v-btn>
  </div>
</template>

<script>
export default {
  data: () => ({
   mesage:{
    msg:"Saved successfully",
    color:'red',
    status:1
  }
}), 

  methods: {
    sendPrameter: function() {      
      this.$emit("emitForm", this.mesage);
    }
  }
};
</script>

https://vuejs.org/v2/guide/components-custom-events.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM