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 (i.e, 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
There are still times where you can use arrow functions with all their benefits, for instance if you assign a function to a variable within one of your Vue instance's methods. Then you can access this within this arrow function, and it would point to the Vue instance as you would expect.
To specify the type of prop you want to use in Vue, you will use an object instead of an array. You'll use the name of the property as the key of each property, and the type as the value. If the type of the data passed does not match the prop type, Vue sends an alert (in development mode) in the console with a warning.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With