weaver
weaver

Reputation: 453

vue js data value return undefined inside method

I am trying to access data value reviews into scroll method . Consoled reviews by console.log(this.reviews). but it always returns undifined;

data() {
  return {
    m: '',
    rating: '',
    review: '',
    visibility: '',
    reviews: [],
    page: 1,
  };
},



scroll (page) { 
  $('#profile-edits-more').on("scroll", function() {      
    if(jQuery(this).scrollTop() + jQuery(this).innerHeight() >= this.scrollHeight) { 
      var vm = this;
      axios.post('./fetch-reviews?page='+page, {
        m: vm.m,
      })
      .then(response => {
        page +=1; 
        console.log(this.reviews);
      });       
    }
  });
},

Upvotes: 0

Views: 258

Answers (1)

gleam
gleam

Reputation: 870

Wrong this try:

scroll (page) { 
  var vm = this;
  $('#profile-edits-more').on("scroll", function() {      
    if(jQuery(this).scrollTop() + jQuery(this).innerHeight() >= this.scrollHeight) { 
      axios.post('./fetch-reviews?page='+page, {
        m: vm.m,
      })
      .then(response => {
        vm.page += 1; 
        console.log(vm.reviews);
      });
    }
  });
},

UPD:

$('#profile-edits-more').on("scroll", ===> function() <=== {

Expression function() ... creates a new scope (with new this). You can also use arrow-methods for such things:

scroll(page) { 
  let $el = $('#profile-edits-more');
  $el.on('scroll', () => {
    if ($el.scrollTop() + $el.innerHeight() >= $el.scrollHeight) { 
      axios.post('./fetch-reviews?page='+page, {
        m: this.m,
      })
      .then(response => {
        this.page += 1; 
        console.log(this.reviews);
      });
    }
  });
},

Upvotes: 1

Related Questions