首页 > 解决方案 > Vuejs 去抖动一个被监视的属性并使用 VueX 调用存储

问题描述

在一个基本组件中,我正在尝试对监视的属性进行去抖动并使用 VueX 存储:

import _ from 'lodash';
import { mapGetters } from 'vuex';

export default {
    name: "search-filters",
    data() {
        return {
            test: 'test'
        }
    },
    watch: {
      linkName: 'checkLinkName',
    },
    computed: {
        ...mapGetters({
            routeLinkName: 'linkName',
        })
    },
    methods: {
        checkLinkName: _.debounce((newVal, oldVal) => {
            console.log(newVal, oldVal, this.test);
            // this.$store.commit('something') is not working too
        }).bind(this)
    }
}

我得到了旧值和新值,checkLinkName但我无法访问测试属性(或 $store,或映射的 getter)。

我试过类似的东西:linkName: _.debounce(this.checkLinkName, 180) 但它告诉 checkLinkName 不是一个函数。

我试图创建自己的去抖动功能:

const debounce = function(fn, time, context) {
    let timeout;
    return function() {
        const functionCall = () => fn.apply(context, arguments);
        clearTimeout(timeout);
        timeout = setTimeout(functionCall, time);
    }
};

但仍然未定义。

标签: vue.jsvuejs2vuex

解决方案


您遇到了绑定上下文的问题this,请尝试在 denounce 调用中使用箭头符号。

data () {
    return {
        debouncer: null
    }
},
created () {
    this.debouncer = _.debounce((newVal, oldVal) => { 
      console.log(newVal, oldVal, this.test)
      this.$store.commit('something')
    }, 250)

    this.debouncer.bind(this)
},
watch: {
  linkName: this.debouncer
},

推荐阅读