Search code examples
vue.jslifecycle

Why can't my vuejs component's mounted hook reference some methods from the same component?


I have a Vue js component. The mounted hook can call some methods and not others. For example, my mounted hook can call the printSomething() method, but not showLayers().

  mounted() {
      this.printSomething()
      this.showLayers();
  },
  methods: {
    printSomething() {
      console.log("hello world");
    },
    showLayers() {
      var tempSelectedLayers = []; 
      for (var i = 0; i < this.layers.length; i++) {
        var layer = this.layers[i];
        console.log(layer.layerName + ", " + layer.checked);
        if (layer.checked == true) {
          tempSelectedLayers.push(layer);
        }
      }
      eventBus.$emit(
        "showLayers",
        tempSelectedLayers
      );
    },

The vue cli displays the error message:

vue.esm.js?a026:628 [Vue warn]: Error in event handler for "showLayers": "TypeError: _this.showLayers is not a function"

It is clear from testing my code at a local host url that the showLayers() function is indeed called despite the error message. If I remove the call to showLayers() from the mounted hook, then the desired behavior does not occur. This suggests the error is related to a race condition. If so, how can I resolve this? Cheers


Solution

  • The error is not referring to your call to the showLayers method in the mounted hook. As you said, the method is being called. The error is referring to this code which also uses the name showLayers:

          eventBus.$emit(
            "showLayers",
            tempSelectedLayers
          );
    

    Check the component that you are emitting to.