0

In the Vue data object there are the following variables defined:

  data: function() {
    return {
      sails: document.querySelectorAll('.sail'),
      sailsGroup: document.getElementsByClassName("sail"),
      nameDisplay: document.querySelector('#name'),
      lines: document.getElementById("lines"),
      texts: document.getElementById("texts")
    }
  },
(...)

Then, there is this showData() method, in the very same Vue object:

showData() {
  console.log(sails);
  console.log(sailsGroup);
  console.log(nameDisplay);
  console.log(lines);
  console.log(texts);
},
(...)

When the method above is called from mounted() hook, it gives: ReferenceError: nameDisplay is not defined at VueComponent.showData. The error appears in case of nameDisplay and sails variables, so the ones assigned with document.querySelector(All) methods. Calling them with this only gives empty array/value.

Why is it so? How to define variables to have them accessible?

AbreQueVoy
  • 840
  • 4
  • 18
  • 35

1 Answers1

1
showData() {
  console.log(sails);
  console.log(sailsGroup);
  console.log(nameDisplay);
  console.log(lines);
  console.log(texts);
},

This references variables in some outer scope. But if those are actually attributes you set up in data, then you need to use this.name instead:

showData() {
  console.log(this.sails);
  console.log(this.sailsGroup);
  console.log(this.nameDisplay);
  console.log(this.lines);
  console.log(this.texts);
},

Note that if those elements are elements that are inside the Vue component’s template, then it’s unlikely that you will find any elements since the component (and its data) is constructed before the component is actually mounted to the DOM. So the querySelectorAll calls run before the component is rendered.

In that case, you should either initialize the data later (once the component has been mounted), or use component refs instead.

poke
  • 307,619
  • 61
  • 472
  • 533