使用Vue"这个" Lodash函数中的实例

时间:2017-10-05 15:07:00

标签: vue.js lodash

使用VueJS并在其中导入Lodash。当使用诸如_.forEach之类的lodash函数时,函数体内的this引用lodash实例。如何让this指向Vue组件的实例?

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

                }

            });

1 个答案:

答案 0 :(得分:5)

您可以使用arrow function。箭头函数中的this值是从它所在的范围中获取的,在这种情况下是Vue组件实例。

示例:

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>