父组件
new Vue({
el:'#app',
data:{
msg:''
},
ready:function(){
this.$http.get('url').then(function(data){
this.msg=data;//假设data=ceshi
})
}
})
<child msg='msg'></child>
子组件
export default {
props: ['msg'],
ready () {
this.msg // undefined (怎么获取?)
}
}
<child msg='msg'></child>
这个写法传入的静态的数据,比如按你所写的,正常来说在自组建中this.msg应该等于你传入的'msg'这个字符串本身,而不是你ajax回来的数据。动态传入用
<child :msg='msg'></child>
但这也不应该是undefined的原因,把完整的代码发一下吧。
老问题,this
指向问题,改改:
new Vue({
el:'#app',
data:{
msg:''
},
ready:function(){
this.$http.get('url').then(data => {
this.msg=data;
});
}
})
补充:
首先,你之前的父组件this
指向是错的,我上面的解答仍然有效。
其次,关于父组件异步获取数据,子组件在ready
里拿不到的问题,通过$watch
来做也不失为一种方法:
export default {
props: ['msg'],
ready () {
this.$watch('msg', function(newVal, oldVal){
console.log('newVal');//这里再感受下值拿到了没
});
}
}
我来提供另一种思路好了,虽然有些麻烦( ̄┰ ̄*)。
使用Vue中的自定义事件
通讯路径:父组件ajax成功返回之后broadcast
一个事件给子组件,子组件监听这个事件然后给子组件中的msg赋值。