深入探讨前端组件化开发

原文链接 :深入探讨前端组件化开发

生命周期

一个组件,需要明确知道在生命周期的不同阶段做该做的事。

初始化阶段,读取属性的值,如果需要做数据和逻辑处理的话,在这个阶段进行。

属性值变化时,如果属性发生变化,且需要对变化后的数据进行处理的话,在这个阶段进行处理。

组件销毁阶段,如果组件已经创建了一些可能会对系统产生一些副作用的东西,可以在这个阶段进行清除。比如 timeInterval、timeout 等。

如果组件在渲染的时候报错,需要展示错误信息。React v16 中提供了 componentDidCatch 生命周期函数,Vue v2.5 中提供了 errorCaptured 的钩子函数。

React 中提供了一些生命周期函数:componentWillMount,componentDidMount,componentWillReceiveProps,shouldComponentUpdate,componentWillUpdate,componentDidUpdate,render,componentWillUnmount,componentDidCatch(React v16)。

Vue 中提供了一些生命周期函数:beforeCreate,created,beforeMount,mounted,beforeUpdate,updated,beforeDestroy,destroyed,errorCapture,errorCaptured(Vue v2.5)。

每个生命周期的具体用法,请参考官方详细文档。

事件传递

Vue 中传递事件很简单,只需要在子组件内使用 this.$emit(‘event1’) 即可向外传递一个事件 event1,在父组件调用该子组件时,只需要监听 event1 事件,并给出对应事件处理逻辑即可。

Vue中事件传递

Vue子组件定义 child-component.vue


深入探讨前端组件化开发_第1张图片

你可能感兴趣的:(深入探讨前端组件化开发)