【问题标题】:Use Vue "this" instance within Lodash function在 Lodash 函数中使用 Vue “this” 实例
【发布时间】:2018-03-17 06:30:57
【问题描述】:

使用 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
                {

                }

            });

【问题讨论】:

  • 谢谢thanksd,但可能不是。并且对于这个简单问题的解决方案可能过于深入。 @asemahle 的解决方案解决了它。
  • 我相信这是完全相同的问题,而 asemahle 的解决方案正是那里接受的答案中的解决方案之一。我建议通读这篇文章,以更好地了解this 的范围一般是如何工作的。
  • 谢谢,真的会看看。

标签: vue.js lodash


【解决方案1】:

您可以使用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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-07-29
    • 2019-08-15
    • 2019-02-04
    • 2017-08-08
    • 2020-01-17
    • 1970-01-01
    • 2017-09-29
    • 2021-03-17
    相关资源
    最近更新 更多