Vue:观看数组数据变量不起作用

时间:2019-02-26 21:41:58

标签: vue.js

我正在尝试查看在数据方法(“ validated”变量)中声明的数组。我已经有一个输入监视程序(legal_name),它可以正常工作,但是数组监视程序没有给出任何响应。任何想法?

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;
        }
    }
}

1 个答案:

答案 0 :(得分:0)

您需要为数组调用Vue.set(),并且使用索引,例如

foo[3]= 'bar'

Vue 可以识别某些操作,例如splicepush

https://vuejs.org/2016/02/06/common-gotchas/https://vuejs.org/v2/guide/list.html#Array-Change-Detection

上了解有关此内容的更多信息

因此对于您的代码,并使用Vue方便的辅助方法$set

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

为什么...

JavaScript没有为数组索引运算符([])提供钩子(重载),因此Vue无法拦截它。这是Javascript的限制,而不是Vue的限制。有关此内容的更多信息:How would you overload the [] operator in javascript