无法将Vuex操作识别为组件的data()中的函数

时间:2019-01-03 10:22:20

标签: vue.js vuex

我在触发vue组件中的方法时遇到问题。我将Vuex与Element UI结合使用,并希望在单击datetimepicker元素中的快捷方式时触发状态更改(使其他组件可见)。这是组件代码:

<template>
    <div id="DateTimePicker">
        <div/>
        TimeInterval state: {{this.$store.getters.timeInterval}}
        <div/>
        <el-date-picker
            :value="this.timeInterval"
            @input="this.setTimeInterval"
            type="datetimerange"
            :picker-options="dateTimeShortcuts"
            range-separator="To"
            format="yyyy-MM-dd HH:mm"
            editable
            time-arrow-control
            start-placeholder="Start date"
            end-placeholder="End date"
            align="right"
            size="large">
        </el-date-picker>
    </div>
</template>

<script>
import { mapGetters, mapActions } from 'vuex'

export default {
    name: 'DateTimePicker',
    computed: {
        ...mapGetters(['timeInterval']),
    },
    methods: {
        ...mapActions(['setTimeInterval', 'setRefreshRateVisibility']),
    },
    data() {
        return {
            dateTimeShortcuts: {
                disabledDate(date) {
                    return date > new Date() || date < new Date('12/1/18');
                },
                shortcuts: [
                    {
                        text: '15 Minutes',
                        onClick(picker) {
                            this.setRefreshRateVisibility(true); // Vue does not recognize this as a function
                            const end = new Date();
                            const start = new Date();
                            start.setTime(start.getTime() - 900 * 1000);
                            picker.$emit('pick', [start, end]);
                        },
                    },
                ],
            },
        };
    },
};
</script>

当我单击快捷方式时,出现错误:

Uncaught TypeError: this.setRefreshRateVisibility is not a function

当我这样做

<div id="DateTimePicker" @click="this.setRefreshRateVisibility(true)">

它工作正常,所以问题不在于动作本身,而是我如何调用此动作。这是商店文件:

export default {
    state: {
        isRefreshRateVisible: false,
    },
    mutations: {
        SET_VISIBILITY(state, newValue) {
            state.isRefreshRateVisible = newValue;
        },
    },
    actions: {
        setRefreshRateVisibility: ({ commit }, newValue) => {
            commit('SET_VISIBILITY', newValue);
        },
    },
    getters: {
        isRefreshRateVisible: state => state.isRefreshRateVisible,
    },
};

请问有人可以帮我掩护吗?

1 个答案:

答案 0 :(得分:0)

您似乎对this的引用有误。在JavaScript上下文中,this指的是直接上下文,但是Vue函数与类/组件的上下文绑定在一起。

为防止这种情况,请将其引用复制到另一个变量中。

data(){
   let componentObj = this;
   ...

然后使用该引用调用该方法。

onClick(picker) {
    componentObj.setRefreshRateVisibility(true);