Front-end componentized development, has many years of history, whether server-side rendering, or front-end SPA, have a relatively mature componentized development scheme. With the popularity of componentized development, there are many good front-end components in the front-end community that provide out-of-the-box solutions to take advantage of componentized development. If someone in the front-end team does not have a deep understanding of front-end componentization, they will not be able to develop good components, which will bring more costs to the maintenance of the project. Read the full text for about 8 minutes.
Author: zollero
This article was first published in the front micro blog of Zhihu column (jump to the front micro blog of wechat public account)
React, Vue or Angular? By now, the ecosystem of frameworks (libraries) is getting better and better, and the performance gap is no longer worth discussing. React and Vue are the most popular entertainment industry in China, while Angular has a low domestic market share due to historical reasons.
With the development of tools such as jade, less, SCSS, typeScript and Webpack, the efficiency of front-end component-based development has been greatly improved.
In particular, the popularity of excellent front-end component libraries such as Ant Design, Element UI and iView has pushed componentized development to the extreme. Developing a front-end page has become very efficient, especially when doing a management system page, scaffolding, adding dependencies, configuring routes, creating pages, importing components, and quickly building a system.
If you need SEO, React and Vue’s SSR frameworks Next-.js and Nuxt.js provide out-of-the box integration solutions and make It much easier to develop “homogeneous page systems” (Google It).
Let’s cut to the chase and dive into the front-end components.
What is front-end componentized development
First, what is front-end componentized development?
You’ve probably encountered situations where hundreds or even thousands of lines of code logic for a page are written in a JS file. Often this kind of code is hard to read, let alone maintain, add new features, or remove old ones, because you don’t know if you’re going to change a place and have an unexpected bug.
At this point, you need to use component-based development, break down functionality, encapsulate components, and maintain them separately.
Modern front-end frameworks are often implementations of MVVM, where the data layer (M) and view layer (V) are connected and changed simultaneously, allowing a high degree of consistency in page interaction.
If you are familiar with Java, Python, Go and other back-end development languages, you should be familiar with the concept of Package. The componentization of the front end is conceptually similar to the package of the back end, but the front end components involve more logic for presentation and interaction. Of course, the front-end component is similar to the microservice concept of the back-end architecture, which can be understood as a component being a service component, providing only one service.
Front-end componentization development is to separate a part of the page, encapsulate the data layer (M), view layer (V) and control layer (C) of this part into a component in the form of black box, and expose some out-of-the-box functions and attributes for external components to call.
A front-end component, including HTML, CSS, JavaScript, including the template of the component, style and interaction content, basically covers all the content of the component, as long as the external component in accordance with the set properties, functions and event processing can be called, completely do not consider the internal implementation logic of the component, for the external, The component is a complete black box.
Components can be wrapped in multiple layers, by calling multiple widgets, and finally wrapped into one large component for external invocation. For example, an Input box is a component, and a Select drop-down box is a component. You can wrap a form layer over both components, which is a component of a Form.
Some common front-end components, such as VUE-Router, Vuex, React-Router, Redux, mobx, etc., are based on VUE and React components. They only focus on routing and state storage and do these things well.
As long as the use of componentized development, the development of a page, just like building blocks, the various components spliced together, finally merged together, is a complete system.
Advantages of componentized development
In the final analysis, the componentized development of the front end can greatly reduce the coupling of the various functions of the system, and improve the cohesion of the internal functions. This has great benefits in terms of front-end engineering and reduced code maintenance.
The reduction of coupling improves the extensibility of the system, reduces the complexity of development, improves the development efficiency and reduces the development cost.
Components are packaged well, there’s less overtime, fewer bugs, and more time for coffee and pesticides. 🙂
How to design a component
Since front-end componentization development is so good, how do you design a good component?
After many times of practice, summed up some key points of component design.
single-minded
To design a good component, components also need to be specific.
Designing components follows a principle: a component focuses on doing one thing and doing it well.
If a function can be divided into multiple function points, each function point can be encapsulated into a component. Of course, the smaller the granularity of the component, the better. As long as the functions and logic in a component are controlled in a controllable range.
Let me give you an example. With a Table list and a paging control on a page, you can wrap the Table as a component, the paging control as a component, and finally the Table component and the paging component as a component. Table components can also be divided into multiple table-column components, and display logic, etc.
configurability
A component whose inputs and outputs are defined.
In addition to displaying the default content, components also need to make some dynamic adaptations, such as: a component has a text, an image, and a button. So the color of the font, the rules of the image, the position of the button, the processing logic of the button click event, and so on, can be made configurable.
The most basic way to achieve configurability is to pass configured values to components through properties, and to read property values to make corresponding display changes during the declaration cycle of component initialization. There are also ways to pass a valid value to a function by calling the component’s exposed function; Modify global CSS styles; Passing a specific event to a component and listening for that event within the component to execute functions, etc.
When you do configurability, you need to do some validation to make components more robust and to ensure that components receive valid properties and functions receive valid parameters.
Verification of the value of an attribute
When verifying the value of an attribute, the following aspects are generally considered.
1. Whether the type of the attribute value is valid. If a property requires passing an array, an exception is thrown and a hint is given if the value passed is not an array.
2. Whether the attribute is required. If the value of some attributes is indispensable in the component, it must be mandatory. During the initialization of the component, check whether it is passed or not. If it is not passed, it needs to throw an exception and give the corresponding prompt. If the property is not required, you can set a default value. If the property is not set, the default value is used.
You can easily set up property checks for components thanks to the built-in property checks implemented by React and Vue, which are performed by default during component initialization. In React, you can use React.PropTypes to set type checking. In Vue, you only need to set props for the component.
Type check in React:
// title. JSX (title Component) import React, {Component, PropTypes} from 'React '; export default class Title extends Component { constructor(props) { super(props); } static propTypes = { title: PropTypes.string.isRequired } render() { const { title } = this.props; return ( <p>{ title }</p> ) }}
Copy the code
Type checking in Vue:
// title. Vue (title component) <template> <p>{{title}}</p> </template> <script> export default {props: {title: {type: String, required: true } } } </script>
Copy the code
Two. Function parameter verification
Function parameter verification, as long as in accordance with the traditional method can be verified. Check the value and type of the parameter at the top of the function. If the parameter does not meet the requirements, it will throw an exception and give the corresponding prompt.
Determines the first required field of a function in String format
ChangeTitle (title) {if (typeof title! == 'string') {throw new Error(' you must pass in a title to change the title. This.setstate ({// react syntax, modify state)}}
Copy the code
The life cycle
A component needs to know exactly what to do at different stages of its life cycle.
Initialization phase, reads the value of the property, and performs data and logic processing if necessary.
When the value of an attribute changes, if the attribute changes and the changed data needs to be processed, it is processed in this phase.
Component destruction phase, where a component can be cleaned up if it has created something that might have some side effects on the system. Such as timeInterval and timeout.
If the component reported an error while rendering, display the error message. React V16 provides the componentDidCatch lifecycle function, and Vue V2.5 provides the errorCaptured hook function.
React provides some lifecycle functions: ComponentWillMount, componentDidMount componentWillReceiveProps, shouldComponentUpdate componentWillUpdate, ComponentDidUpdate, Render, componentWillUnmount, componentDidCatch(React V16)
Some lifecycle functions are provided in Vue: BeforeCreate, created, beforeMount, Mounted, beforeUpdate, updated, beforeDestroy, destroyed, errorCapture, ErrorCaptured (Vue v2.5).
Please refer to the official documentation for detailed usage of each lifecycle.
events
This.$emit(‘ event1 ‘) is used within the child component to send event1. When the parent component calls the child component, it only needs to listen for the event1 event and provide the corresponding event processing logic.
Event passing in Vue
The Vue child defines child-component.vue
Vue.component('child-component', {
methods: {
emitEvent() {
this.$emit('event1', 'This is a event.')
}
},
mounted() {
this.emitEvent()
}
})
Copy the code
The Vue parent component calls the child component
<template>
<div>
<child-component @event1="eventHandler" />
</div>
</template>
<script>
import childComponent from './child-component'
export default {
components: {
childComponent
},
methods: {
eventHandler(event) {
console.log(event)
}
}
}
</script>
Copy the code
In React, there is no official solution for event transfer between components, which is another disadvantage of React. However, there are other ways to do this.
React, the parent component can use props to value children, father and child components to component value, need to define functions within the parent component and through property passed to the child components, within the child component by calling the attributes corresponding function, the incoming parameters, passed to the function inside the parent component, and do logic in the parent component of the function of processing.
The React child component defines child-component.js
class ChildComponent extends React.Components {
render() {
return (
<button onClick={
() => {
this.props.clickHandler('This is a click')
}
}></button>
)
}
}
Copy the code
React Parent component calls child component
import ChildComponent from './child-component'
class ParentComponent extends React.Components {
clickHandler(message) {
console.log(message)
}
render() {
return (
<child-component
clickHandler={ this.clickHandler.bind(this) }
/>
)
}
}
Copy the code
Afterword.
The practice of front-end componentized development is a very long process, which persists and continues to optimize to drive the overall optimization of the system.
This article will be updated later on “how to develop a VUE third-party component”.
There will be more React and Vue articles to follow.
Related previous articles
Vue v2.5 adjustments and updates are not fully explained
React 16 introduces a new concept called exception boundaries that allows you to handle in-module exceptions better
Use Next. Js to quickly start rendering the React server
Front-end era after front and back end separation