0

i'm trying to watch an array declarated in data method (the 'validated' variable). I already have a watcher to an input (legal_name) and it works correctly but the array watcher doesnt give any response. Any idea?

export default {
    data() {
        return {
            legal_name : '',
            validated: [],
            errors: []
        }
    },
    watch: {
        validated() {
            console.log('modified')
        },
        legal_name(value) {
            this.eventName();
            this.legal_name = value;
            this.checkLength(value, 3);
        }
    },
    methods: {
        checkLength(value, lengthRequired) {
            if(value.length < lengthRequired) {
                this.errors[name] = `Debes ingresar al menos ${lengthRequired} caracteres`;
                this.validated[name] = false;
                return false;
            }

            this.errors[name] = '';
            this.validated[name] = true;
            return true;
        },
        eventName() {
            name = event.target.name;
        }
    }
}
Ken Ramirez
  • 325
  • 5
  • 17

1 Answers1

0

You need to call Vue.set() for arrays, and NOT use indexing such as

foo[3]= 'bar'

Vue DOES recognize some operations, such as splice and push, however.

Read more about it here: https://vuejs.org/2016/02/06/common-gotchas/ and here: https://v2.vuejs.org/v2/guide/list.html#Array-Change-Detection

So for your code, and using the Vue handy helper method $set:

this.validated.$set(name, true);

Why...

Javascript does not offer a hook (overload) for the array index operator ([]), so Vue has no way of intercepting it. This is a limitation of Javascript, not Vue. Here's more on that: How would you overload the [] operator in javascript

tony19
  • 125,647
  • 18
  • 229
  • 307
Steven Spungin
  • 27,002
  • 5
  • 88
  • 78