【问题标题】:VueJS this in lodash throttled methodVueJS this in lodash 节流方法
【发布时间】:2017-08-13 02:40:36
【问题描述】:

我正在尝试限制我的 VueJS 应用程序中的方法。我一开始尝试了以下方法:

export default {
    data () {
        return {
            foo: 'bar'
        }
    },
    methods: {
        doSomething () {
            console.log('olas')
        }
    },
    created () {
        _.throttle(this.doSomething,200)
    }
}

但是 doSomething 方法没有被触发:https://jsfiddle.net/z4peade0/

然后,我尝试了这个:

export default {
    data () {
        return {
            foo: 'bar'
        }
    },
    methods: {
        doSomething: _.throttle( () => {
            console.log('olas')
        },200)
    },
    created () {
        this.doSomething()
    }
}

函数g被触发:https://jsfiddle.net/z4peade0/1/

问题是,我无法访问节流方法内的foo 属性:

export default {
    data () {
        return {
            foo: 'bar'
        }
    },
    methods: {
        doSomething: _.throttle( () => {
            console.log(this.foo) // undefined
        },200)
    },
    created () {
        this.doSomething()
    }
}

我试图做类似的事情:

const self = {
    ...
    methods: {
        doSomething: _.throttle( () => {
            console.log(self.foo) 
        },200)
    },
    ...
}

export default self

没有成功

如何在 VueJS 方法上使用 lodash 节流方法,并使用 this 上下文?

【问题讨论】:

    标签: vue.js lodash


    【解决方案1】:

    您使用的箭头函数绑定了错误的上下文 (this)。你应该使用普通的function

        doSomething: _.throttle( function () {
            console.log('olas', this.foo);
        },200)
    

    【讨论】:

    • 效果很好,我完全不知道,非常感谢
    猜你喜欢
    • 2022-08-11
    • 2019-12-14
    • 1970-01-01
    • 1970-01-01
    • 2021-11-30
    • 2017-11-26
    • 2018-05-31
    • 2020-12-03
    • 2019-01-27
    相关资源
    最近更新 更多