使用VueJS并在其中导入Lodash.当使用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
{
}
});
Run Code Online (Sandbox Code Playgroud)
您可以使用箭头功能.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);
})
}
})Run Code Online (Sandbox Code Playgroud)
<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>Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
469 次 |
| 最近记录: |