Vuejs取消监视的属性并使用VueX呼叫商店

时间:2018-08-21 12:59:27

标签: vue.js vuejs2 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);
    }
};

但仍然不确定。

1 个答案:

答案 0 :(得分:1)

您遇到this绑定上下文的问题,请尝试在谴责电话中使用箭头符号。

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
},