Solve the problem that the value passed by the parent component cannot be obtained when the child component sends the request

Problem Description

When parent-child components communicate, the parent component passes a value, and the child component receives the value and initiates the request as a parameter of the request. But there is no result after the request is initiated, and the value is printed and found to be empty.

父组件
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)    //打印结果为空
	 	//发送请求
}

Cause Analysis

Because the props attribute to be passed in the parent component is returned through an ajax request, the request process takes time, but the rendering of the child component is faster than the ajax request process, so created and mounted will only be executed once at this time The life cycle hook has been executed, but the props have not yet come in (subcomponent), so only the default value can be obtained.

Solution

1. Call the method in the child component through the parent component and pass parameters

父组件
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 to do the delay, but not accurate (not recommended)

子组件
props:['sn']
created () {
    
    
	setTimeout(() => {
    
    
        this.getData()
      }, 2000);
},
methods(){
    
    
	getData(){
    
    
	 	console.log(this.sn)    
	 	//发送请求
}

3. Watch monitoring parameters (recommended)

子组件
props:['sn'],
methods(){
    
    
	getData(){
    
    
	 	console.log(this.sn)    //打印结果有值
	 	//发送请求
}
watch: {
    
    
    sn:function(newData) {
    
    
      this.sn = newData   //可以读取到sn的值后再进行请求
      this.getData()
    }
  }

Guess you like

Origin blog.csdn.net/qq_58648235/article/details/127134765