Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

486
Visualizações
Vue JS - variable from javascript module is not reactive

I created a small module as a validator inspired from vee-validate and I would like to use this in conjunction with the composition api. I have a list of errorMessages that are stored in a reactive array, however when I retrieve this variable in my vue component, despite the error messages being stored in the array accordingly, the variable is not updating in the vue template.

I’m not very savvy with this so I might not be concise with my explanation. The refs in the module seem to be working properly. Can someone kindly indicate what I might be doing wrong? I'm completely stuck and I don't know how else I can proceed.

Validator.js (Npm module - located in node_modules)

import Vue from 'vue';
import VueCompositionAPI from '@vue/composition-api'
import {ref} from '@vue/composition-api'

Vue.use(VueCompositionAPI)

class Validator {
….

register({fieldName, rules, type}) {
    if (!fieldName || rules === null || rules === undefined) {
      console.error('Please pass in fieldName and rules');
      return false;
    }
    let errorMessages = ref([]);
    // define callback for pub-sub
    const callback = ({id, messages}) => {
      if (fieldId === id) {
        errorMessages.value = Object.assign([], messages);
        console.log(errorMessages.value); // this contains the value of the error messages.
      }
    };
    return {
      errorMessages,
    };
  }
……

InputField.vue

<template>
  <div :style="{'width': fieldWidth}" class="form-group">
    <label :for="fieldName">
      <input
        ref="inputField"
        :type="type"
        :id="fieldName"
        :name="fieldName"
        :class="[{'field-error': apiError || errorMessages.length > 0}, {'read-only-input': isReadOnly}]"
        @input="handleInput"
        v-model="input"
        class="form-input"/>
    </label>
    <div>
      <p class="text-error">{{errorMessages}}</p> // Error messages not displaying
    </div>
  </div>
</template>

<script>
  import {ref, watch} from '@vue/composition-api';
  import Validator from "validator";

  export default {
    props: {
      fieldTitle: {
        required: true
      },
      fieldName: {
        required: true
      },
      type: {
        required: true
      },
      rules: {
        default: 'required'
      }
    },
    setup(props) {
      // The error messages are returned in the component but they are not reactive. Therefore they only appear after its re-rendered.
      const {errorMessages, handleInput, setFieldData} = Validator.register(props);

      return {
        errorMessages,
        handleInput,
      }
    }
  }
</script>
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You should be using Vue.Set(), it directly triggers related values to be updated

about 4 years ago · Juan Pablo Isaza Relatório

0

The problem is Validator.register() directly destructures props, which removes the reactivity from the resulting values.

Solution

Use toRefs(props) to create an object of refs for each prop, and pass that to Validator.register():

import { toRefs } from 'vue'
                      👇 
Validator.register(toRefs(props))

Then update Validator.register() to unwrap the refs where needed:

class Validator {
  register({ fieldName, rules, type }) {
                    👇             👇                       👇
    if (!fieldName.value || rules.value === null || rules.value === undefined) {
      console.error('Please pass in fieldName and rules');
      return false;
    }
    ⋮
  }
}
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda