解决子组件发送请求时获取不到父组件传递的值
问题描述
在父子组件通信时,父组件传递一个值,子组件接收这个值并作为请求的参数来发起请求。但是在发起请求之后没有结果,打印这个值发现为空。
父组件
data () {
return {
sn:''
}
},
created () {
this.getSn()
},
methods(){
getSn(){
//发送请求获取sn参数
this.sn = res.data.sn
}
<child :sn='sn'></child>
子组件
props:['sn']
created () {
this.getData()
},
methods(){
getData(){
console.log(this.sn) //打印结果为空
//发送请求
}
原因分析
因为父组件中要传递的props属性是通过发生ajax请求回来的, 请求的这个过程是需要时间的,但是子组件的渲染要快于ajax请求过程,所以此时 created 、mounted这样的只会执行一次的生命周期钩子,已经执行了,但是props还没有进来(子组件),所以只能拿到默认值。
解决方法
1.通过父组件调用子组件中的方法并传递参数
父组件
data () {
return {
sn:''
}
},
created () {
this.getSn()
},
methods(){
getSn(){
//发送请求获取sn参数
this.sn = res.data.sn
this.$refs.childRef.getData(this.sn)
}
<child :sn='sn' ref='childRef'></child>
2.setTimeout来做延迟,但不准确(不推荐)
子组件
props:['sn']
created () {
setTimeout(() => {
this.getData()
}, 2000);
},
methods(){
getData(){
console.log(this.sn)
//发送请求
}
3.watch监听参数(推荐)
子组件
props:['sn'],
methods(){
getData(){
console.log(this.sn) //打印结果有值
//发送请求
}
watch: {
sn:function(newData) {
this.sn = newData //可以读取到sn的值后再进行请求
this.getData()
}
}