1

Using VueJS and importing Lodash therein. When using a lodash function such as _.forEach, this within the function body refers to the lodash instance. How do I make this to point to the Vue component's instance instead?

_.forEach(records, function(val)
            {
                if (this.max_records >0) // max_records is defined in data(), so this should be the cimponent instance
                {

                }

            });
gthuo
  • 2,376
  • 5
  • 23
  • 30
  • 1
    Possible duplicate of [How to access the correct \`this\` inside a callback?](https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback) – thanksd Oct 05 '17 at 15:12
  • thanks thanksd, but probably not. And may be too indepth a solution to this simple issue. @asemahle's solution solved it. – gthuo Oct 05 '17 at 15:20
  • 1
    I believe this is the exact same problem and asemahle's solution is exactly one of the solutions in the accepted answer there. I would recommend reading through the post to get a better understanding of how the scope of `this` works in general. – thanksd Oct 05 '17 at 15:24
  • thanks, will really have a look at it. – gthuo Oct 05 '17 at 15:30

1 Answers1

5

You can use an arrow function. The this value in an arrow function is fetched from the scope it sits inside, which in this case is the Vue component instance.

Example:

new Vue({
  el: '#app',
  data: {
    message: 'Hello'
  },
  created() {
    // we use an arrow function, so that 'this' refers to the component
    _.forEach([1,2,3], (e) => {
      console.log(this.message + ' ' + e);
    })
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.4/vue.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>
<div id="app">
  <p>Look at the output in the console! We see that the correct "this" was used.</p>
</div>
asemahle
  • 20,235
  • 4
  • 40
  • 38