1

I have vue2 component where I want to access a data object variable to use in template. Pertinent code: Template:

<div v-html="theWivesBios[currentWife]" class="modal-content"></div>

Script:

export default {
  name: "theSixWives",
  data() {
    return {
      theWivesBios: theWivesBios,
      currentWife: ""
    };
  },
  mounted() {
    elContainer.addEventListener("click", function(ev) {
      //Want to manipulate this.currentWife in callback
      this.currentWife = "testing"; // this.currentWife isnt available to vue instance
    }

What would be best way to "hoist" this.currentWife so the vue instance would have access to it for use in my template?

Phil
  • 157,677
  • 23
  • 242
  • 245
Alan
  • 1,067
  • 1
  • 23
  • 37
  • Use an arrow function for your event handler, ie `elContainer.addEventListener("click", ev => { this.currentWife = "testing" })` – Phil Mar 18 '21 at 23:03
  • You can "store" this before .addEventListener like `const self = this;`. Inside listener function use `self.currentWife = 'testing';`. Arrow function is better solution. – J. Kovacevic Mar 19 '21 at 10:44

1 Answers1

2

You have to use an arrow function like this:

export default {
  name: "theSixWives",
  data() {
    return {
      theWivesBios,
      currentWife: ""
    };
  },
  mounted() {
    elContainer.addEventListener("click", () => {
      this.currentWife = "testing";
    });
  }
}

This answer explains very well how this works on regular and arrow functions: https://stackoverflow.com/a/20279485/7699022

Hope it helped!

  • 1
    Yes thank you. So used to being told not to use arrow functions in Vue methods. I assume this works because this is now being taken from lexical scope? – Alan Mar 19 '21 at 16:00