mapGetters 仅在第一次加载时出现反应性问题

Sim*_*eau 5 javascript store vue.js vuex vue-reactivity

我正在使用mapGettersVueX的帮助程序,但我只在页面的第一次加载时遇到了一些问题,它不是反应性的......让我告诉你:

我的 html 模板触发更改:

<input type="number" value="this.inputValue" @change="this.$store.dispatch('setInputValue', $event.target.value)">
Run Code Online (Sandbox Code Playgroud)

我的商店收到价值

{
    state: {
        appValues: {
            inputValue: null
        },
    },
    getters: {
        getInputValue: (state) => {
            return state.appValues.inputValue;
        },
    },
    mutations: {
        setInputValue(state, value) {
            state.appValues.inputValue = value;
        },
    },
    actions: {
        setInputValue(context, payload) {
            return new Promise((resolve, reject) => {
                context.commit('setInputValue', payload);
                resolve();
            });
        },
    }
}
Run Code Online (Sandbox Code Playgroud)

然后我的组件监听商店:

import {mapGetters} from 'vuex';

computed: {
    ...mapGetters({
        inputValue: 'getInputValue',
    }),
}
watch: {
    inputValue: {
        deep: true,
        immediate: true,
        handler(nVal, oVal) {
            console.log("inputValue", nVal, oVal);
        }
    },
}
Run Code Online (Sandbox Code Playgroud)

所以现在,当我第一次加载页面时,我得到了这个 console.log "inputValue" null undefined,这是完全正常的,因为我的商店里没有任何东西,它给了我默认值null

但现在是奇怪的部分。我开始更改输入值,但控制台中没有显示任何内容。什么都没有动...

然后我重新加载页面并在加载时得到这个 console.log "inputValue" 5 undefined(5 是我之前输入的值)所以你可以看到,当我之前更改输入时,它很好地将值保留在商店中,但是计算出来的价值没有自我更新......

现在,当我更改输入的值时,我的控制台日志是这样的,"inputValue" 7 5所以它的工作方式就像我希望它从一开始就工作......

我做错了什么?为什么在第一次加载时计算出的值没有反应?

谢谢你的回答...

小智 1

我认为解决这个问题的最好方法是用观察器存储本地变量,然后在本地更改时更新 vuex:

在您的组件上:

<input type="number" v-model="value">

Run Code Online (Sandbox Code Playgroud)
data() {
    return {
        value: ''
    };
},

computed: {
    ...mapGetters({
        inputValue: 'getInputValue'
    })
}

watch: {
    value(value){
        this.$store.dispatch('setInputValue', value);
    },

    inputValue(value) {
        console.log('inputValue', value);
    }
},

created() {
    // set the initial value to be the same as the one in vuex
    this.value = this.inputValue;
}
Run Code Online (Sandbox Code Playgroud)