这是执行顺序的问题。主 Vue 实例在它里面的东西被编译之前还没有“准备好”。这包括hello组件。
如果您需要在使用它之前知道bar已设置,您可以通过几种方式对其进行监控。您可以$broadcast在父母中的一个事件让孩子知道bar已加载。或者您可以使用watch子组件中的函数在bar更新时进行更改。
如果您$set barin created(),您的示例确实有效,但是无论如何vue-resource您都会有延迟,因此您需要考虑在孩子的功能greeting期间不会准备好的事实。ready()你要么必须设计你的 DOM 结构来处理greeting可能的事实undefined,要么你必须使用一个事件或watch函数来自己等待它。
示例$broadcast:
Vue.component('hello', {
template: 'From hello tag: {{ greeting }}',
props: ['greeting'],
ready: function() {
},
events:{
'bar-ready':function(){
alert(this.greeting)
}
}
});
new Vue({
el: '#app',
created: function() {
this.$http.get('/path')
.then(function(response){
this.$set('bar',response.data);
this.$broadcast('bar-ready')
}.bind(this))
}
});
$broadcast文档:https ://vuejs.org/api/#vm-broadcast