【发布时间】:2019-04-04 11:58:35
【问题描述】:
我已经建立了一个简单的 vue 项目来显示问题。我唯一添加的是 axios 包。问题是当我尝试在异步调用后设置子组件的属性时,我无法读取组件中的该属性。如果您查看代码,您会看到我多次控制台日志以显示何时可以获取数据以及何时无法获取数据。请帮我弄清楚我在这里缺少什么。
父母
<template>
<div id="app">
<HelloWorld :test_prop="testData" :test_prop2="testData2" :test_prop3="testData3" test_prop4="I work also"/>
<div>{{testData5}}</div>
</div>
</template>
<script>
import HelloWorld from './components/HelloWorld.vue'
import axios from 'axios';
export default {
name: 'app',
components: {
HelloWorld
},
data() {
return {
testData: '',
testData2: 'I work just fine',
testData3: '',
testData5: ''
}
},
created: function(){
var self = this;
this.testDate3 = 'I dont work';
axios.get('https://jsonplaceholder.typicode.com/posts/42').then(function(response){
//I need this one to work
self.testData = 'I dont work either';
self.testData5 = 'I work also';
});
}
}
</script>
孩子
<template>
</template>
<script>
export default {
name: 'HelloWorld',
props: ['test_prop', 'test_prop2', 'test_prop3', 'test_prop4'],
data() {
return {
comp_data: this.test_prop,
comp_data2: this.test_prop2,
comp_data3: this.test_prop3,
comp_data4: this.test_prop4
}
},
created: function(){
console.log(this.test_prop);
console.log(this.test_prop2);
console.log(this.test_prop3);
console.log(this.test_prop4);
}
}
</script>
【问题讨论】:
-
您好,您似乎在此处复制代码。或者这只是一个糟糕的复制/粘贴,但你的两个组件是相同的。
-
谢谢我复制错了。
-
当您更改
testData值时,您是否希望comp_data值发生变化? -
只有在最初创建时才会在父级上调用。之后它不需要来自父母的任何数据。在实际项目中,我试图让孩子从父母那里获取初始数据,然后从那时起在内部设置自己。
标签: asynchronous vue.js vue-component