Vuejs: How to share data from one component to another?

Asked

Viewed 1,592 times

1

I have two separate components and need that when clicking on a button, it modifies the variable of another component.

For example I have the following component:

var componenteFiltroBusca = new Vue({
     el: '#componenteFiltroBusca',
     data: {
        buscadorText: '(por n° de cupón, importe)',
     }
});

And when I click a button that’s inside the:

var tabMovimientos = new Vue({
    el: '#tabMovimientos',
})

I need him to change the text inside the seekerText, how to do this?

  • What is the relationship between them? Do they have any component in common? they are descendants?

  • they have no relationship

2 answers

3


If the components have no relationship you can create a $bus, or a channel via Vue.prototype and that all components can use to send and listen to events.

Vue.prototype.$bus = new Vue({});

and then on the components you can do like this:

// para avisar o canal de eventos
this.$bus.$emit('increment', a, b, c);

// para receber eventos
this.$bus.$on('increment', function(a, b, c){
  // etc...
});

Implemented:

Vue.prototype.$bus = new Vue({});
new Vue({
    el: '#botao',
    data: {
        count: 0
    },
    methods: {
        updateCount() {
            this.count++;
            this.$bus.$emit('increment', this.count);
        }
    }
});

new Vue({
    el: '#mostrador',
    data: {
        contador: 0,
    },
    created() {
        this.$bus.$on('increment', val => this.contador = val);
    }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.2/vue.min.js"></script>
<div id="botao">
    <button type="submit" @click="updateCount">
        Incrementar
    </button>
</div>
<div id="mostrador">
    {{contador}}
</div>

0

Have two elegant ways to do this, or you instantiate the other component within your own and pass the new values via props

Or you use Vuex to build a directional architecture. I hope I’ve helped!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.