Veer3383
Veer3383

Reputation: 1825

Why my vue js data member is not getting updated?

Data part

  data () {
    return {
      containsAd: true
    }
  },

Method that manipulates the data member containsAd

  updated () {
    let _this = this
    window.googletag.pubads().addEventListener('slotRenderEnded', function (event) {
      if (event.slot.getSlotElementId() === 'div-gpt-ad-nativead1') {
        _this.containsAd = !event.isEmpty // this is false
        console.log('Ad Exists? ', _this.containsAd)
      }
    })
  },

Just to check if the value has changed or not.

check () {
  let _this = this
  setTimeout(function () {
    console.log('Current Value', _this.containsAd)
  }, 5000)
}

Resulting Output

enter image description here

Upvotes: 0

Views: 48

Answers (1)

Rich
Rich

Reputation: 562

I think doing the event listener in the mounted hook will sort your issue.

data() {
    return {
        containsAd: true
    };
},

mounted() {
    window.googletag.pubads().addEventListener('slotRenderEnded', event => {
        if (event.slot.getSlotElementId() === 'div-gpt-ad-nativead1') {
            this.containsAd = ! event.isEmpty // this is false
            console.log('Ad Exists?', this.containsAd);
        }
    });
}

Also using es6 shorthand function will avoid you having to set _this.

Upvotes: 2

Related Questions