Vue父组件mounted执行完后再执行子组件mounted

需求背景

我们在父组件中的 mounted 生命周期钩子函数中执行百度地图的初始化创建;

在子组件的 mounted 中,调用接口,将数据坐标点添加到地图上。

<!-- parent-component.vue -->
<template>
  <div class="map" id="map"></div>
  <child-component></child-component>
</template>

<script>
export default {
      
      
  data() {
      
      
	return {
      
      
	  map: null
	}
  },
  mounted() {
      
      
    // 创建地图实例
	this.map = new BMap.Map('map')
  }
}
</script>
<!-- child-component.vue -->
<template>
  <div>...</div>
</template>

<script>
export default {
      
      
  mounted() {
      
      
    // 下面这一行是模拟调用接口的情况,返回一个数据
    let point = this.$ajax.getPoint()
    // 创建一个点,将点添加到地图中
    this.$parent.map.addOverly(point)
  }
}
</script>

现在这样可能会报错,因为父组件中的 map 还没创建成功。必须确保父组件的 map 创建完成,才能使用 this.$parent.map 的方法。

那么,现在的问题是:如何保证父组件 mounted 结束后再进行子组件 mounted

深入分析

你需要了解父子组件生命周期的执行顺序

父子组件生命周期执行顺序

父组件先进行创建,在挂载(mounted)前,子组件进行创建+挂载,子组件挂载完成后父组件挂载。
整个顺序就是:

父组件:beforeCreate
父组件:created
父组件:beforeMount
子组件:beforeCreate
子组件:createc
子组件:beforeMount
子组件:mounted
父组件:mounted

可以看出是先子组件 mounted 之后父组件 mounted,那么,如何实现父组件 mounted 完毕后再子组件 mounted 呢?

解决办法

【思路】 通过打印 this 发现,有一个 _isMounted 属性,表示当前是否挂载完毕(true:挂载完毕,false:没有挂载完成),在父组件挂载前将 _isMounted 存在 window 中,挂载后更新 _isMounted。在子组件 mounted 中添加定时器,根据 _isMounted 判断是否执行初始化方法。

// 父组件
beforeMount() {
    
    
	window.parentMounted = this._isMounted	// _isMounted是当前实例mouned()是否执行 此时为false
},
async mounted() {
    
    
	await GaodeMap().then(() => {
    
    
		// ...
	})
	window.parentMounted = this._isMounted	// _isMounted是当前实例mouned()是否执行 此时为true
}
// 子组件
mounted() {
    
    
    let pMountedTimer = window.setInterval(() => {
    
    
        if (window.parentMounted ) {
    
    
	        window.clearInterval(pMountedTimer)
	        // 下面就可以写子组件想在mounted时执行代码(此时父组件的mounted已经执行完毕)
			this.initData()
        }
    }, 500)
}

[拓展]生命周期执行顺序

  • 子组件更新过程
- 父beforeUpdate -> 子beforeUpdate -> 子updated -> 父updated
  • 父组件更新过程
- 影响到子组件: -  父beforeUpdate -> 子beforeUpdate -> 子updated -> 父updated
- 不影响子组件: -  父beforeUpdate -> 父updated
  • 销毁过程
- 父beforeDestroy -> 子beforeDestroy -> 子destroyed -> 父destroyed

-----------------(正文完)------------------

前端学习交流群,想进来面基的,可以加群:
Vue学习交流 React学习交流
或者手动search群号:685486827832485817


写在最后: 约定优于配置 —— 软件开发的简约原则
-------------------------------- (完)--------------------------------------

我的:
个人网站: https://neveryu.github.io/neveryu/
Github: https://github.com/Neveryu
新浪微博: https://weibo.com/Neveryu

更多学习资源请关注我的新浪微博…

猜你喜欢

转载自blog.csdn.net/csdn_yudong/article/details/113035397