使用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
{
}
});
答案 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>