I'm probably missing some concept of VueJS so I need help on this one. I made an example to make my question more clear. Let's say I have some multipurpose component like modal window. I'm grabbing data from Vuex.
./components/modal.vue
<script>
export default {
methods: {
modalClose() {
this.$store.commit("modalClose");
},
},
computed: {
body() {
return this.$store.state.modal.body;
},
footer() {
return this.$store.state.modal.footer;
},
show() {
return this.$store.state.modal.show;
},
},
};
</script>
<template>
<div class="wrap" @click.self="modalClose" v-if="show">
<div id="modal" class="modal">
<div class="modal-body" v-html="this.body">body</div>
<div class="modal-footer" v-html="this.footer">footer</div>
</div>
</div>
</template>
<style>
/* whatever */
</style>
And I have another component which set Vuex data and use my modal component to show the data. And it works fine - it presents the data. But at some point I need to work with the data inside the modal window and this is where I'm losing it.
./components/persons.vue
<script>
export default {
data: function () {
return {
persons: [
{ name: "John Johnson", id: 1 },
{ name: "David Lynch", id: 2 },
{ name: "Marshall Attack", id: 3 },
],
};
},
methods: {
showModal: function (person) {
this.$store.commit("modal", {
body: "Name: " + person.name,
footer: `<a href="#" person-id="${person.id}">Add</a>`,
});
},
addPerson: function (id) {
// how to trigger this function with "Add" button?
console.log("Success! Person " + id + " was added!");
},
},
};
</script>
<template>
<div id="page1">
<div v-for="person in persons" :key="person.id">
{{ person.name }}
<a href="#" @click="showModal(person)"> Open modal </a>
</div>
</div>
</template>
In this example you can see method addPerson. It belongs to persons.vue and it suppose to be executed (argument required) with click on "Add" button inside the modal window. So, I have two questions:
- How can I do it?
- Am I populating bad practices?
P.S. I read about $emit but I didn't have any luck with it.