javascript - 在 Vue 中操作完成之前,Getter 返回与输入值相同的值

标签 javascript vue.js vuex

我为功能 X 创建了一个组件和一个模块,并且使用 Vuex 进行状态管理。该代码适用于每次第一次插入,但此后 Getter 函数始终在操作结束并提交突变之前返回相同的输入值。

例如:
1 - 一切都是 [0,0,0],Getter 是 [0,0,0]。在第一个位置插入9,值就被插入了。
2 - 第二次,检查插入的值是否等于状态上的值返回 true,因此我们必须删除此验证。

顺便说一句,状态会继续修改,而操作不会将更改提交到突变,并且当我们查看 Getter(从状态检索值)时,插入的值已经由 Getter 返回。

有人知道如何解决这个问题吗?

这是代码

组件:

Vue.component('profundidade-cell', {

    data: function () {
        return {
            valorProfundidade: [0, 0, 0],
            id: this.face + '-' + this.dente,
            ids: [
                this.face + '-profundidade-sondagem-' + this.dente + '-1',
                this.face + '-profundidade-sondagem-' + this.dente + '-2',
                this.face + '-profundidade-sondagem-' + this.dente + '-3'
            ],
            changedId: null,
            valorInserido: null,
            valorAnt: null,
        }
    },

    props: {
        arcada: String,
        sextante: String,
        dente: String,
        face: String,
        face_json: String,
        max_length: Number,
        min_value: Number,
        max_value: Number,
    },

    computed: {
        profundidadeSondagem() {
            return store.getters['profundidadeSondagem/profundidadeSondagem']({arcada: this.arcada,
                sextante: this.sextante, dente: "dente_" + this.dente, face: this.face_json});
        },

        presente() {
            return store.getters.dentePresente({arcada: this.arcada, sextante: this.sextante,
                dente: "dente_" + this.dente});
        }

    },

    created: function() {
        this.debouncedAlterarProfundidade = _.debounce(this.alterarValorProfundidadeSondagem, 400);
        this.$root.$on("vuex-carregado", this.carregar);
    },

    methods: {

        getValue(e) {
            this.changedId = e.target.id;
            this.valorInserido = e.target.value;

            this.debouncedAlterarProfundidade();


        },

        alterarValorProfundidadeSondagem() {

            let modelRefs = {};

            let patologia = {
                arcada: this.arcada,
                sextante: this.sextante,
                dente: "dente_" + this.dente,
                face: this.face_json,
                valor: this.valorProfundidade,
                modelRefs: modelRefs,
                id: this.changedId,
                valorInserido: this.valorInserido,
            };

            store.dispatch('profundidadeSondagem/MODIFY', patologia).catch(() => {

                this.valorProfundidade = this.profundidadeSondagem;
            })

        },

        carregar(){
            this.valorProfundidade = this.profundidadeSondagem;
        }

    },


    template: `
        <div>
            <input type="text" :id=ids[0] v-on:input.prevent="getValue($event)" :maxlength=max_length v-model=valorProfundidade[0] class="periograma-input col l4" v-bind:class="{ 'invisible': !presente }" />
            <input type="text" :id=ids[1] v-on:input.prevent="getValue($event)" :maxlength=max_length v-model=valorProfundidade[1] class="periograma-input col l4" v-bind:class="{ 'invisible': !presente }" />
            <input type="text" :id=ids[2] v-on:input.prevent="getValue($event)" :maxlength=max_length v-model=valorProfundidade[2] class="periograma-input col l4" v-bind:class="{ 'invisible': !presente }" />    
        </div>
    `

});

模块:

const moduleProfundidadeSondagem = {
    namespaced: true,

    actions: {
        MODIFY({commit, dispatch, getters, rootGetters}, obj) {
            let patologia = {
                face: rootGetters.getNomeFace(obj.face),
                dente: rootGetters.getNomeDente(obj.dente),
                local: "FACE",
                ficha: this.state.idPeriograma,
                descricao: obj.valor.toString(),
                paciente: this.state.idPaciente,
                tipo: 'PROFUNDIDADE_DE_SONDAGEM'
            };

            if(obj.valor) != getters.profundidadeSondagem(obj)) {

                let reg = new RegExp(/([0-9],[0-9],[0-9])/);

                let param = null;

                return new Promise((resolve, reject) => {
                    if(obj.valor[0] == 0 && obj.valor[1] == 0 && obj.valor[2] == 0) {
                        param = axios.delete('/patologia', {data: patologia});
                    } else if (reg.test(obj.valor)){
                        param = axios.post('/patologia', patologia);
                    }

                    if(param != null) {
                        param.then(function (response) {
                            if(response.status == 200 || response.status == 201 && response.data) {
                                commit('armazenarProfundidadeSondagem', obj);

                                let dentes_data = {};
                                let face = '';

                                if (obj.arcada == 'arcada_superior' && obj.face == 'face_lingual_palatal') {
                                    face = 'palatina'
                                } else {
                                    face = obj.face.split('_')[1];
                                }


                                let classe_canvas = rootGetters.getNomeClasseCanvas(obj, face);

                                drawGraph(rootGetters.prepareDentesData(obj, face, dentes_data), face,
                                    classe_canvas);
                                resolve();
                            }

                        }).catch(error => {

                            store.dispatch('mensagemAlerta/ALERTA', {
                                tipo: 'error',
                                mensagem: 'Não foi possível cadastrar o nível de sondagem'
                            });

                            reject(error);
                        });
                    }
                })
            }
        },

        RESET_PROFUNDIDADE_SONDAGEM({commit}, ob) {
            commit('RESET_ALL', ob);
        }
    },

    getters: {
        profundidadeSondagem: (state, getters, rootState) => obj => {
            return rootState[obj.arcada][obj.sextante][obj.dente][obj.face].profundidade_sondagem;
        }
    },


最佳答案

我的猜测是你的问题出在这里:

<小时/>

TL;DR - 你将 getter 作为勇气传递给你的行动。

<小时/>

只是猜测 - 因为我无法调试你的代码

<小时/>
        store.dispatch('profundidadeSondagem/MODIFY', patologia).catch(() => {

            this.valorProfundidade = this.profundidadeSondagem;
        })

当您从 rootState[...] 分配引用时,您会更改组件中第一个之后的 rootState[...] 的属性运行。

所以你的代码的行为如下:

        let patologia = {
            arcada: this.arcada,
            sextante: this.sextante,
            dente: "dente_" + this.dente,
            face: this.face_json,
            
          // valor: this.valorProfundidade,
          ///* same as */ valor: this.profundidadeSondagem,
          /* same as */ valor: this.$store.getters['profundidadeSondagem/profundidadeSondagem'](...),
            modelRefs: modelRefs,
            id: this.changedId,
            valorInserido: this.valorInserido,
        };
<小时/>

解决方案可以是 this.valorProfundidade = this.profundidadeSondagem.slice(); 只要它是数组或 Object.assign({},...) code> - 这样你就可以防止引用

关于javascript - 在 Vue 中操作完成之前,Getter 返回与输入值相同的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56876675/

相关文章:

javascript - 将 JS var 传递给 PHP var

javascript - JQuery $function() 触发什么事件?

javascript - VueJS 应用程序将 GET 请求中的数据放入数组中

vue.js - 右键单击vuejs应用程序时出错

vue.js - Vuex store 在 Nuxt 中的什么位置

javascript - 向下滚动时标题不透明度不改变

javascript - 在Javascript中绑定(bind)回调函数? (不要与 Function.prototype.bind() 混淆)

javascript - Axios catch 错误返回 JavaScript 错误而不是服务器响应

javascript - 迭代时设置对象的属性

javascript - 升级 npm 包后功能变慢