[Vue warn]: Error in created hook: "TypeError: Cannot set property of undefined"

20,258

Solution 1

Don't use arrow functions to define methods. See the warning box at https://vuejs.org/v2/guide/instance.html#Data-and-Methods

Solution 2

this in an arrow function refers to the parent context, so here it's referring to the window object, not the Vue object.

Instead of convertMins: (minutes) => {}, use convertMins(minutes) {}.

Share:
20,258
CoderPJ
Author by

CoderPJ

Updated on July 09, 2022

Comments

  • CoderPJ
    CoderPJ almost 2 years

    I am creating a VueJS application. I have a child component, Child.vue to which data is passed from a parent.

    Child.vue

    export default{
    
        props:['info'],
    
        data: function(){
            return{
                timeValue:{
                    minutes: '',
                    hours: ''
                }
            }
        },
        created: function(){
            
            console.log("Printing inside created of Child ",this.info);
            this.convertMins(this.info[0][2]);
            
        },
    
        methods:{
            convertMins: (minutes) => {
                console.log("Printing inside convert mins", this);
                if(minutes===0){
                    this.timeValue.minutes = 0;
                    this.timeValue.hours = 0;
                }
                if(minutes===60){
                    this.timeValue.hours = 1;
                    this.timeValue.minutes = 0;
                }
                if(minutes>60){
                    this.timeValue.hours = Math.floor(minutes/60);
                    this.timeValue.minutes = minutes % 60;
                }
            }
        }
    
    }

    And my parent component looks like this,

    Parent.vue

    import Child from './Child.vue';
    
    export default {
    data(){
    	return{
            info:[ ],
    
            errors: []
    	}
    },
    
    created: function(){
    
      this.accessInformation();
    },
    
    methods: {
        
        accessInformation: function(){
        axios.get(localhost:3000/retrieveInfo)
        .then(response =>{
        console.log(response.data.rows[3]);
        this.info.push(response.data.rows[3]);
       })
       .catch(e => {
                this.errors.push(e);
       })
     }
    },
    
    components: {								
        'child': Child,
        
      }
    }
    <template>
     <div>
       <child v-bind:info="info" v-if="info.length > 0"></child>
     </div>
    </template>

    When I try running the application, I get an error like this,

    Error

    enter image description here

    Why I am getting this error? I am new to VueJS. Can someone please help me out here?

  • Fathy
    Fathy over 3 years
    in my case was typo in ".then"