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
                {

                }

            });
4
  • 1
    Possible duplicate of How to access the correct `this` inside a callback? Commented Oct 5, 2017 at 15:12
  • thanks thanksd, but probably not. And may be too indepth a solution to this simple issue. @asemahle's solution solved it. Commented Oct 5, 2017 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. Commented Oct 5, 2017 at 15:24
  • thanks, will really have a look at it. Commented Oct 5, 2017 at 15:30

1 Answer 1

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>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.