javascript [Vue 警告]:创建的钩子出错:“TypeError:无法设置未定义的属性”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/47525044/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
[Vue warn]: Error in created hook: "TypeError: Cannot set property of undefined"
提问by CoderPJ
I am creating a VueJS application. I have a child component, Child.vue to which data is passed from a parent.
我正在创建一个 VueJS 应用程序。我有一个子组件 Child.vue,数据从父组件传递到该组件。
Child.vue
儿童.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
父.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,
当我尝试运行应用程序时,出现这样的错误,
Why I am getting this error? I am new to VueJS. Can someone please help me out here?
为什么我收到这个错误?我是 VueJS 的新手。有人可以帮我吗?
回答by Botje
Don't use arrow functions to define methods. See the warning box at https://vuejs.org/v2/guide/instance.html#Data-and-Methods
不要使用箭头函数来定义方法。请参阅https://vuejs.org/v2/guide/instance.html#Data-and-Methods 上的警告框
回答by Jpod
thisin an arrow function refers to the parent context, so here it's referring to the windowobject, not the Vueobject.
this在箭头函数中是指父上下文,所以这里指的是window对象,而不是Vue对象。
Instead of convertMins: (minutes) => {}, use convertMins(minutes) {}.
而不是convertMins: (minutes) => {},使用convertMins(minutes) {}。


