首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在Lodash函数中使用Vue "this“实例

在Lodash函数中使用Vue "this“实例
EN

Stack Overflow用户
提问于 2017-10-05 15:07:00
回答 1查看 699关注 0票数 1

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

代码语言:javascript
复制
_.forEach(records, function(val)
            {
                if (this.max_records >0) // max_records is defined in data(), so this should be the cimponent instance
                {

                }

            });
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-10-05 15:11:20

您可以使用箭头函数。箭头函数中的this值是从它位于其中的范围中获取的,在本例中是Vue组件实例。

示例:

代码语言:javascript
复制
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);
    })
  }
})
代码语言:javascript
复制
<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>

票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46588990

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档