Avoid mutating a prop directly in VueJS 2

前端 未结 1 926
日久生厌
日久生厌 2021-01-19 01:24

First of all, I am just starting playing with VueJS, so this cannot be a VueJS version thing as suggested here

It might be a duplicate of :

  • How to solv
1条回答
  •  后悔当初
    2021-01-19 01:53

    The warning is the result of setting v-model to the value of your properties. The reason is because if you change birthYear, birthMonth, or birthDay outside the component, then whatever the value is currently inside the component will be immediately overwritten.

    Instead, capture a copy.

    Vue.component('birthday-controls', {
    
        template: `
    `, props: ['birthDay', 'birthMonth', 'birthYear'], data(){ return { internalBirthDay: this.birthDay, internalBirthMonth: this.birthMonth, internalBirthYear: this.birthYear } }, computed: { validYear: function() { return (this.internalBirthYear > new Date().getFullYear()-100 && this.internalBirthYear < new Date().getFullYear()-14) }, validMonth: function() { return (this.internalBirthMonth > 0 && this.internalBirthMonth <= 12) }, validDay: function() { return (this.internalBirthDay > 0 && this.internalBirthDay <=31) //I have to add more checking here for february, leap years and .... } } });

    You did this almost exactly in your fiddle, but you did not correct your computed values.

    computed: {
        validYear: function() {
            return (this.birthYear > new Date().getFullYear()-100 && this.birthYear < new Date().getFullYear()-14)
        },
        validMonth: function() {
            return (this.birthMonth > 0 && this.birthMonth <= 12)
        },
        validDay: function() {
            return (this.birthDay > 0 && this.birthDay <=31) //I have to add more checking here for february, leap years and stuff
        }
    },
    

    should be

    computed: {
        validYear: function() {
            return (this.var_birthYear > new Date().getFullYear()-100 && this.var_birthYear < new Date().getFullYear()-14)
        },
        validMonth: function() {
            return (this.var_birthMonth > 0 && this.var_birthMonth <= 12)
        },
        validDay: function() {
            return (this.var_birthDay > 0 && this.var_birthDay <=31) //I have to add more checking here for february, leap years and stuff
        }
    },
    

    0 讨论(0)
提交回复
热议问题