【问题标题】:[Vue warn]: Error in created hook: "TypeError: Cannot set property of undefined"[Vue 警告]:创建钩子时出错:“TypeError:无法设置未定义的属性”
【发布时间】:2018-05-11 12:35:32
【问题描述】:

我正在创建一个 VueJS 应用程序。我有一个子组件 Child.vue,数据从父组件传递到该组件。

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

}

而我的父组件看起来像这样,

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>

当我尝试运行应用程序时,出现这样的错误,

为什么我会收到此错误?我是 VueJS 的新手。有人可以帮我吗?

【问题讨论】:

    标签: javascript html vue.js vuejs2 vue-component


    【解决方案1】:

    不要使用箭头函数来定义方法。查看https://vuejs.org/v2/guide/instance.html#Data-and-Methods的警告框

    【讨论】:

    • 在我的情况下是“.then”中的拼写错误
    【解决方案2】:
    箭头函数中的

    this 指的是父上下文,所以这里指的是 window 对象,而不是 Vue 对象。

    请使用convertMins(minutes) {},而不是convertMins: (minutes) =&gt; {}

    【讨论】:

      猜你喜欢
      • 2019-06-04
      • 2020-04-13
      • 2021-02-06
      • 1970-01-01
      • 2021-12-22
      • 2021-12-19
      • 2021-02-17
      • 2021-06-04
      • 2018-07-14
      相关资源
      最近更新 更多