为什么我的 vuejs 组件的 mounted hook 不能引用同一个组件的一些方法?

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

我有一个 Vue js 组件。 mounted hook 可以调用某些方法,但不能调用其他方法。例如,我挂载的钩子可以调用 printSomething() 方法,但不能调用 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
      );
    },

vue cli 显示错误信息:

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

通过在本地主机 url 上测试我的代码可以清楚地看出,尽管有错误消息,但确实调用了 showLayers() 函数。如果我从已安装的挂钩中删除对 showLayers() 的调用,则不会发生所需的行为。这表明该错误与竞争条件有关。如果是这样,我该如何解决?干杯

错误不是指您在挂载挂钩中调用 showLayers 方法。如您所说,正在调用该方法。错误是指此代码也使用名称 showLayers:

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

检查您要发射到的组件。