Use component data in the create method in VueJs

0

I'm trying to pass data from one component to another using the $ bus method:

Vue.component('porcentagens',{
data: function(){
    return {
        porcentagemSangramentoMarginal: 0,
        porcentagemPlaca: 0,
        porcentagemOLeary: 0,

        selecionadosSangramentoMarginal: [],
        selecionadosPlaca: [],
        selecionadosPorcentagemOLeary: []
    }
},

created(){
    this.$bus.$on('faceSelecionada', function(idFaceSelecionada){

        if(idFaceSelecionada.charAt(0) == 's'){

        }

    })
},

He is listening to the event 'faceSelected' normally and receiving the parameter as well, but I can not access the data of the component itself: when receiving the event with parameter I need to add the received id in the list within date and change the value that also is contained in date, but it can not access at all, I've already tried using this and $.

    
asked by anonymous 08.10.2018 / 15:32

1 answer

0
The problem is that using a "normal" function ( function ) changes the execution context, and the this within that function is not what you expect ...

You have two solutions:

Uses Arrow functions

And so the this is the same as it was outside the function:

created(){
    this.$bus.$on('faceSelecionada',(idFaceSelecionada) => {
        if(idFaceSelecionada.charAt(0) == 's'){

        }
    })
},

Uses an alias for this

If you make const self = this; out of the function you can then use self instead of this within function because that variable is not changed.

created(){
    const self = this;
    this.$bus.$on('faceSelecionada', function(idFaceSelecionada){

        if(idFaceSelecionada.charAt(0) == 's'){
          // aqui podes usar self.algumaPropriedadeReactiva = idFaceSelecionada;
        }

    })
},
    
12.10.2018 / 07:45