使用VueJS并在其中导入Lodash。当使用诸如_.forEach之类的传入函数时,函数体中的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
{
}
});发布于 2017-10-05 15:11:20
您可以使用箭头函数。箭头函数中的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>
https://stackoverflow.com/questions/46588990
复制相似问题