Using component data in the create method in Vuejs

Asked

Viewed 32 times

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 too, but I cannot 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 is also contained in date, but it cannot access it at all, I tried using this and $.

  • Try to use Lifecycle mounted in place of created

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:

Usa 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'){

        }
    })
},

Use an alias for the this

If you do const self = this; out of the function you can then use the self in time of this within the function because this 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;
        }

    })
},

Browser other questions tagged

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