I have 2 components inside /resources/assets/js/components, the first one has:
<template>
<div class="inline">
<button @click="getDataCategory(category)" :class="is_active == category.id ? 'btn-primary' : 'btn-default' " v-for='category in categories' class='btn btn-space'>{{category.name}}</button>
</div>
</template>
<script>
import BaseUrlMixin from '../mixins/baseUrl.js';
export default {
mixins: [BaseUrlMixin],
data(){
return{
id_tournament:null,
categories:[],
data_category: false,
is_active: false,
show_data: "",
}
},
methods: {
getDataCategory: function(category){
this.is_active = category.id;
this.show_data = {
'category':category.name
};
this.data_category = true;
}
},
}
</script>
The idea is that when you click on the button, call getDataCategory() and there set this.show_data as you see it, and so far it works, now I need to pass that this.show_data to another component that is the following. I want to use as seen in the form the if="show_data" has values to show the form. (I understand that you can put this component inside the other, but due to the structure of the template I can't and I need this communication.
<template>
<div>
<form @submit.prevent="store()" :if="show_data">
<label for="">Cantidad de fechas</label>
<input type="text" v-model="date" onkeypress='return event.charCode >= 48 && event.charCode <= 57' min="1" max="50" required="">
<button class='btn btn-primary btn-sm' >
<i class="fa fa-floppy-o" aria-hidden="true"></i>
Guardar
</button>
</form>
</div>
</template>
<script>
export default {
data(){
return{
id_tournament:null,
date:'',
}
},
methods: {
},
mounted() {
this.getIdTournament();
}
}
</script>
You can create a "Bus" to send communications between components that have no parent-child relationship between them, basically it's an empty Vue instance:
then you do the
$emit
from where you want to send the information:This is how you receive it in the component you want:
This was all taken from the documentation , though I've already used it in practice too.
The two most common ways to communicate between components in Vue is through the event bus pattern and the state management pattern.
Depending on the complexity of the application, you must choose what best suits your needs. Typically, the event bus is used more for communication between isolated components that don't necessarily alter the state of the application.
As an application starts to grow, using a bus becomes increasingly difficult to maintain, and that's when a state management pattern becomes useful. The recommended one is vuex , which is maintained by Evan, the creator of Vue.