preface

The idea of componentization is not unique to the front end, but it is an extension of the front end technology. Any software development process, more or less, has some need for componentization

Rise along with the three big frame, front componentization gradually become the urgent needs of the development of the front-end, a mainstream, a kind of consensus, it not only improve the efficiency of development, but also reducing the costs of d component cohesion principle to protect the developers no longer need to face a pile of arcane code, and only need to pay attention to the code of the components of fragment This is a new challenge!

Before you begin, define your boundaries

  • From front-end engineering to componentized development
  • Design principles for components
  • Functional division of components and pros and cons
  • Component design boundaries
  • How to do it in the specific business
  • Some feeling
  • conclusion

An interview question prompts thoughts

Interviewers often ask, have you written a front-end common component?Copy the code

You might confidently say: Sure!

emm.. Yes?

From front-end engineering to componentized development

Front-end engineering goes through three phases

1. Library/frame selection

2. Simple build optimizations

To solve the development efficiency, but also need to take into account the performance, so choose a build tool, code compression, verification, and then to the page for the unit of simple resource consolidation

3. JS/CSS modular development

After addressing basic development efficiency and operational efficiency, it’s time to consider maintenance efficiency

Divide and conquer (to reduce complexity by decomposition) is an important idea in software engineering, is the cornerstone of complex system development and maintenance, modularity is the front end of the divide and conquer means

So modularity is about splitting, and the biggest value is divide and conquer, meaning that whether or not you want to reuse that piece of code in the future, there’s a reason to break it up into a single module

Take a big problem, break it down into smaller problems, analyze them, and put them back together (divide and conquer)

Modular solution

  • JS modular
No modularity -> function -> object -> self-executing function ->CommonJS/AMD/CMD->ES6 ModuleCopy the code
  • CSS modular
CSS modularity is implemented with the support of less, SASS and other preprocessorsCopy the code

Is that enough?

Certainly not enough

Modularity emphasizes separation, whether from a business perspective or from an architectural or technical perspective. Modularity first means separating code, data, and so on according to their responsibilities

There are some problems with simple horizontal split of business function modules

  • Process-oriented code is less maintainable as the business evolves
As the business grows, the process line gets longer and longer, and other project members add their own logic to the process line according to their own needs, and eventually the logic of the page becomes unmaintainable and we need to get rid of the "cascading" codeCopy the code
  • Just JS/CSS modularity is not enough, UI (page) partition is also more urgent
In addition to JS and CSS, the interface also needs to be split, how to integrate the idea of modularity into HTML languageCopy the code

4. Componentized development (focus of this paper)

Evolution of componentized development

Before the concept of componentized development was touted, there was a search for componentized best practices

Modularization of page structure

And that goes into actual development like this

We can get information

  • The page pageModel containstabContainer.listContainerimgsContainerThree modules
  • We encapsulate different types of Models based on different business logic
  • Each model has its own data, template, logic, and is considered a complete functional unit

Yi? There’s a whiff of componentization

Microsoft’s componentized solution, HTML Component, N years ago

There are always historical relics 🐖

Over N years ago, Microsoft came up with a solution called HTML Component

Is a relatively complete componentization scheme, but failed to enter the standard, quietly disappeared, today’s perspective, it can be said to be born at the wrong time

WebComponents standard

At the time, “so-called components”

  • At this time, components can basically only reach a collection on a functional unit, and resources are all loosely distributed in three resource files
  • Moreover, the component scope is exposed to the global scope, and the lack of cohesion can easily cause conflicts with other components (such as the simplest CSS naming conflicts).

So the W3C is impatient, to develop a WebComponents standard, for the componentization of the future guide the way

There are roughly four functions

  • <template>Define HTML template capabilities for components
  • The Shadow Dom encapsulates the internal structure of a component and keeps it independent
  • Custom Element provides a component tag to implement Custom tags
  • Import handles component binding and dependency loading

Let’s think about what the capabilities are for a practical solution

  • High resource cohesion (High internal cohesion of component resources, component resources are controlled by their own loading)
  • Scope independent (internal structure is sealed and does not affect global or other components)
  • Custom tags (define how components are used)
  • Can be combined with each other (assembly and integration between components)
  • Interface normalization (component interfaces have unified specifications, or lifecycle management)

Three major frameworks emerge

Today’s front-end ecology is divided into React, Angular and Vue. Even though they have different positioning, the core common point is that they provide the ability to componentize, which is the best componentize practice at present

Vue.js uses JSON to describe a component
import PageContainer from './layout/PageContainer'
import PageFilter from './layout/PageFilter'

export default {
  install(Vue) {
    Vue.component('PageContainer', PageContainer)
    Vue.component('PageFilter', PageFilter)
  }
}

Copy the code

The SFC (Single File Component) ‘.vue ‘File format is also available

<template>
//...
</template>

<script>
  export default {
    data(){}
  }
</script>

<style lang="scss"> / /... </style>Copy the code
2. React.js invented JSX to cram CSS and HTML into JS files
class Tabs extends React.Component {
    render() {
        if(! this.props.items) { console.error('Need to pass data in Tabs');
            return null;
        }
        const propId = this.props.id;
        return(<ul className={this.props. ClassName}> <li> </li> </ul>); }}Copy the code
Angular.js selects extensions over the original HTML
<input type="text" ng-model="firstname">

var app = angular.module('myApp'[]); app.controller('formCtrl'.function($scope) {
    $scope.firstname = "John";
});
Copy the code

Resource integration under standards

Has the following characteristics

  • Each component corresponds to a directory where all the resources required by the component are maintained nearby. (most valuable in software engineering)
  • Each individual visual/interactive area on the page is treated as a component;
  • Because the components are independent, they can be combined freely;
  • A page is a container of components, responsible for assembling components to form a fully functional interface;
  • An entire directory can be removed/replaced when a component is not needed or if you want to replace it

Application structure diagram

  • Molecules are made up of atoms, molecules are divided into atoms, and atoms can be recombined to form new molecules
  • An interface is made up of individual molecular components, which are made up of atomic components that can be combined in different ways to form new molecular components that can then be recombined to form new interfaces

Modularity versus componentization

In terms of the overall concept

  • Modularity is the idea of divide and conquer, which calls for decoupling, generally referring to JS modules, such as those used to format time
  • Componentization is the realization means of modularization idea, the appeal is reuse, includingtemplate.style.script, script can be composed of various modules

In terms of reuse

  • Modules are generally divided according to project business content within the scope of a project. For example, a project is divided into subsystems, modules and sub-modules, and code is separated into modules
  • Components are abstracted in terms of the versatility and reusability of small functions that can cross projects and are reusable modules

In terms of historical development

As the front-end development becomes more and more complex and requires higher efficiency, the modular development at project level is further promoted to the componentization development of general functions. Modularity is the premise of componentization, and componentization is the evolution of modularity

Design principles for components

Under the componentization scheme, we need to have the componentization design thinking, which is a kind of [finishing] to help us develop and integrate efficiently

  1. standard
Each component should adhere to a set of standards that allow developers in different areas to develop a standard set of componentsCopy the code
  1. independence
It describes the fine granularity of components, follows the principle of single responsibility, keeps the API such as the pure attribute configuration of components open to the outside world, the internal state of components closed to the outside world, and coupling with business as little as possibleCopy the code
  1. Reuse and ease of use
UI differences are digested within components (note that it is not written in a heapif/elseI/O friendly, easy to useCopy the code
  1. Be short and concise

  2. Apply SPOT law

Single Point Of Truth: Try not to duplicate code.Copy the code
  1. Avoid exposing component internal implementations
  2. Avoid direct manipulation of the DOM, and avoid using refs
Use the parent's state to control the state of the child component instead of manipulating the child component directly through the REFCopy the code
  1. The entry checks the validity of the parameters and the exit checks the correctness of the returns
  2. Acyclic Dependence Principle (ADP)

Improper design leads to a ring dependent schematic

impact

Coupling between components is high, integration testing is difficult to change one at a time, impacts are everywhere, delivery times are long because of cyclic dependencies between components, it becomes a chicken-and-egg problem

So if we really have this problem, how do we deal with it

Elimination of ring dependence

Our quest is to find all affected components along the backward dependencies

Create a new component to be co-dependent on

  1. Stable Abstraction Principle (SAP)
- The degree of abstraction of a component is proportional to its stability, - a stable component should be abstract (logic-independent) - an unstable component should be concrete (logic-related) - to reduce coupling between components, we need to program for abstract components, not for business implementationsCopy the code
  1. Avoid redundancy
If a data can be obtained by another transformation of state, then the data is not a state, just write a transformation handler function, you can use the computation property in Vue. If a data is fixed, does not change, then the data is like a fixed HTML site title, If a sibling component has the same state, then the state should be moved to a higher level and passed to both components using propsCopy the code
  1. Reasonable dependencies
The parent component does not depend on the child component. Deleting a child component does not cause abnormal functionCopy the code
  1. Flattening parameter
In addition to data, avoid complex objects and try to accept only values of primitive typesCopy the code
  1. Good interface design
If a constant becomes props for more scenarios, then it can be props. The old constant can be used as the default. If you need to write a lot of code for specific requirements for a particular caller, consider building a new component, such as an extension. Ensure that component properties and events are sufficient for most components.Copy the code
  1. The API is as consistent as possible with known concepts

Functional division of components

So with the component design “API”, will it be possible to develop high-quality components?

The greatest instability of components comes from the presentation layer, where a component does only one thing, and responsibilities are divided based on function

As a rule of thumb, I would classify components into the following categories

  • Base components (usually solved in the component library)
  • Container Components
  • Stateless component
  • The business component
  • Common component
    • UI components
    • Logical component
  • High order Component (HOC)

Based on the component

In order to make developers more focused on business logic, there are many excellent UI component libraries such as ANTD and Element-UI. We can only call the API for most business scenarios, and the front-end role is put back, making development easier

Container assembly

A container-like component that serves as an entry point to a business submodule, such as a component to which a route is directed

The characteristics of

  • Child components within a container component typically have business or data dependencies
  • Centralized/unified state management, providing data to other presentation/container components (acting as data source) and behavior logic processing (receiving callbacks)
  • If global state management is used, then the business components inside the container can invoke global state to process the business themselves
  • The communication of sub-components in the business module is coordinated and processed, and acts as the status relay station of sub-component communication
  • Templates are mostly collections of child components and rarely containDOMThe label
  • Auxiliary code separation

Form 🌰 (vue)

<template>
<div class="purchase-box"> <! <div class=. <div class=. <div class="scroll-content"> <! -- Search area --> <Search v-show="toggleFilter" :form="form"/ > <! -- Expand the collapse area --> <Toggle :toggleFilter="toggleFilter"/ > <! -- List area --> <List :data="listData"/>
  </div>
</template>
Copy the code

Stateless components

How is the component rendered, like a simple template rendering process

The characteristics of

  • Accepts data and callback functions only through props, and does not act as a data source
  • It may contain presentation and container components and typically has Dom tags and CSS styles
  • Usually use props. Children (react) or slot(vue) to include other components
  • No dependencies on third parties (available for an application-level component)
  • Can be stateful, can manipulate and change its internal state during its lifetime, has a single responsibility, passes behavior that is not its own through callbacks for the parent to handle (search event for search component/add event for form)

Form 🌰 (vue)

 <template>
 <div class="purchase-box">
    <el-table
      :data="data"
      :class="{'is-empty': !data ||  data.length ==0 }"
      >
      <el-table-column
        v-for = "(item, index) in listItemConfig"
        :key="item + index" 
        :prop="item.prop" 
        :label="item.label" 
        :width="item.width ? item.width : ''"
        :min-width="item.minWidth ? item.minWidth : ''"
        :max-width="item.maxWidth ? item.maxWidth : ''"> </el-table-column> <! -- Operation --> <el-table-column label="Operation" align="right" width="60">
        <template slot-scope="scope">
          <slot :data="scope.row" name="listOption"></slot> </template> </el-table-column> <! -- List empty --> <template slot="empty">
        <common-empty />
      </template>
    </el-table>
    
 </div>
  </template>
<script>
  exportDefault {props: {listItemConfig:{// List item configurationtype:Array,
        default: () => {
            return [{
                prop:'sku_name',
                label:'Trade name',
                minWidth:200
            },{
                prop:'sku_code',
                label:'SKU',
                minWidth:120
            },{
                prop:'product_barcode',
                label:'Bar code',
                minWidth:120
            }]
      }
    }}
  }
</script>
Copy the code

The business component

They are usually abstractions based on minimal business state. Some business components are reusable, but most are one-time components

Common component

Components that can be common within one or more apps

UI components

  • Interface extension class components, such as popovers

Features: Strong reusability. Communicates with the external world only through component interfaces such as Props, Events, and Slots

Form 🌰 (vue)

<template>
  <div class="empty">
    <img src="/images/empty.png"</div> </template>Copy the code

Logical component

  • A logical set that does not contain a function of the UI layer

High order Component (HOC)

A higher-order component can be thought of as a combination in functional programming. A higher-order component can be thought of as a function that takes a component as an argument and returns an enhanced component

Higher-order components can abstract methods of a component’s common functions without contaminating your own components such as Debounce and Throttle

Let me draw a graph

High-order components in React are the most common form of component encapsulation. Vue has a built-in high-order component keep-Alive that maintains a cache for data persistence, but does not recommend using HOC (

Writing components in React is writing functions. Functions have functional components with Vue, which are more like highly encapsulated functions, allowing you to accomplish some things easily. However, the opposite of high encapsulation is the loss of flexibility, you need to follow certain rules to make the system run betterCopy the code

🌰 (react)

Animation of brand cars sliding

Various components work together to form a business module

Container/display components

Contrast figure

Introducing the concept of container components is simply a better way to organize things

  • The container component communicates with the Store, passing the data to the presentation component via props. If the presentation component needs to update the data, it needs to pass the callback to the container component, and perform the operation (business logic) in the container component to get the update result
  • The presentation component is no longer directly coupled to the Store. Instead, it uses the props interface to define the required data and methods, ensuring reuse and correctness
  • If a display component communicates directly with a Store, then a display component is limited because your fields in the Store are limited in how many times they can be used and where they can be used
  • Each of them is not easy to make mistakes, and even if they do, they can quickly locate the problem

In that case, when do I introduce container components and when do I introduce presentation components

Timing of the introduction of container components

Give priority to presentation components. Consider introducing container components when you realize that there are intermediate components that don’t use the props they inherit but instead pass them to their children, and you need to readjust those intermediate components every time the children need more data

The distinction between container components and display components is not strictly defined; the difference is not technical but purport

Here are a few points of reference

  • Container components tend to be stateful and display components tend to be stateless. It is not a hard and fast rule that they can both be stateful
  • Don’t make it a dogma to separate container components and display components. If you’re not sure whether the component is a container component or a display component, don’t separate it. It may be too early to write a display component. Don’t worry!
  • It’s a constant refactoring process, and instead of trying to get it right all at once, getting used to this pattern develops an intuition about when to introduce a container just as you know when to encapsulate a function

The pros and cons of dividing component functions

advantages

  • Better separation of attention
By writing components this way, you can get a better understanding of your app and your UI, and even develop your own development routinesCopy the code
  • High reusability
When a component does only one thing, it decouples components and leads to higher reusabilityCopy the code
  • It’s the palette of the app, and the designer can tweak its UI without changing the app’s logic
  • This forces you to extract the “layout components” for greater ease of use
  • Improved robustness
Since the presentation and container components are connected via the Prop interface, the props validation mechanism can be used to enhance code reliability. Hybrid components do not have this benefit. For example 🌰(Vue) props: {editData: Object, statusConfig: {type: Object,
      default() {
        return {
          isShowOption: true// Whether there is an action bar isShowSaveBtn:false}; }}}Copy the code
  • testability
Components do less, and testing is easier. Container components don't care about the presentation of the UI, just the data and updates. Presentation components just render the props that come in, and it's easy to mock the data layer when writing unit testsCopy the code

So-called shortcomings

  • There is some initial learning cost due to the split of container/presentation components
  • The need to encapsulate a container and wrap some data and interfaces to the presentation component can add some work
  • There is a small amount of work involved in displaying the props declaration within the component

In the long run, the advantages outweigh the disadvantages

Component design boundaries

Before you get excited, consider the following questions to guide you in improving your component design

The page level should not be nested more than three levels, do not overdesign

Beyond three layers, the process of transferring data to visible components becomes more complexCopy the code

Can this component be subdivided (if necessary)?

  • Dividing granularity is a tradeoff based on the actual situation, too small will increase maintenance costs, too large will not be flexible and high reuse
  • Each component should have its own distinct division purpose, either for reuse implementation or to encapsulate complexity and clear business implementation
  • Component division is usually based on business logic, function, and whether the relationship between components is clear, and the degree of reusability
  • If it’s just a few lines of code, you might end up creating more code to separate it. Is that necessary? Do the benefits outweigh the costs?
  • If your current logic is unlikely to appear anywhere else, then it’s better to embed it and pull it off if you need to, because componentization has no end
  • Will performance be affected? If the state changes frequently and is currently in a large, closely related component, it is best to pull it out to avoid performance impact
  • Whether a logically meaningful entity is broken, and if so, what is the probability that the code will be reused

Are the dependencies on this component reducible?

Reducing component dependencies increases component reusability

Does this component cause intrusion into other components?

  • Inadequate encapsulation or its own cross-border operation, it may cause an intrusion outside of its own
  • A component should not have a direct impact on a sibling component
A more common scenario is when the component runtime adds a resize listener event to the Window object to enable the component to respond to the window size change event. A better alternative to this requirement is for the component to provide a refresh method that is called by the parent component implementation. A suboptimal solution is to clean up before the component destroysCopy the code

Can this component be replicated in other similar scenarios?

You need to consider the different scenarios that need to be applied, and make the necessary compatibilities when designing component interfaces

How does this component look when someone else is using it?

The interface is designed to conform to the norms and conventions of the public, and to make it as easy as possible for others to use. Easy to use means more intuitive.

If the service does not need this function, is it convenient to clear?

The components cooperate with each other in the relationship of composition, which is also the modular abstraction of functional requirements. When the requirements change, the implementation can be adjusted in the granularity of modules

The above guidelines are just a description of a development concept and can be considered a development specification, but if you agree with the specification and feel comfortable with its dive-and-conquer strategy, then we can move on to its implementation

Ask yourself a question

What’s your idea of a relatively perfect component?

How to do it in the specific business

Classified according to

Be clear about how you divide your components. There are currently two

  • Division by Business
  • Divide by technology
  1. I design the component tree in my application more according to the business, maybe draw a sketch or xmind, which helps me see the big picture
  2. Define the boundaries of each component, the design of the internal state, the design of props, and the relationship with other components (events that need to be called back)
  3. Define the positioning and function division of each component, and design the communication mechanism of father and son components and brother components
  4. which
  5. We have the shelf. Let’s fill in the blanks

Cut templates (page structure modular)

This is the easiest way to think about it. When a component renders many elements, you need to try to separate the rendering logic of those components. Let’s take the nugget page as an example

Generally speaking, it can be divided into Part1, Part2, Part3

Preliminary development

<template>
  <div id="app">
    <div class="panel">
      <div class="part1 left"> <! <div class="part1 right"> <! <div class="part1 right"> <! </div> </div> </template>Copy the code

Question:

  • It’s a lot of code, it’s hard to maintain, it’s hard to test
  • There’s a little bit of repetition

Change numerous for brief

<template>
  <div id="app">
      <part1 />
      <part2 />
      <part3 /> 
  </div>
</template>

Copy the code

Benefits:

  • This subtle improvement over the previous approach is revolutionary
  • The problem of difficult test and maintenance is solved

Question:

  • It does not solve the problem of code duplication, which is divided into modules and low reuse

But I’ve seen a lot of project code, that’s how it works, think I’ve done componentization, abstraction is good (@_@)

Component abstraction

They have a similar outer layer, part2 and part3 have a more similar titlebar, except for the business content, which is exactly the same

🌰 (vue)

<template>
  <div class="part">
    <header>
      <span>{{ title }}</span>
    </header>
    <slot name="content" />
  </div>
</template>


Copy the code

We made all the data that can be abstracted from the part props, and we made the template using the slot so that when we developed the corresponding part 1, part 2

🌰 (vue)

<template>
  <div id="app">
      <part title="Yi shu">
        <div slot="content">----</div>
      </part>
      <part title="Xinglong Zhenyuan Family model">
        <div slot="content">-----</div>
      </part>
  </div>
</template>
Copy the code

More representative example diagram

  • Where are the UI differences defined?

Processing at the business logic layer

First of all, it is important to be clear that these differences are not caused by the component itself, but by your own business logic, so the container component (parent component) should pay for themCopy the code
  • Where are the data differences defined?

The combination of the component itself and the business context eliminates the differences internally

For example, in Part3, other parts only have one link like more >>, but it has multiple (one, two...). I recommend that this difference be reflected inside the component. There are many design methods: For example, link arrays can be changed to links; For example, more >> can be considered a default link, and the extra part can be a special user defined link, combining the two to form links. User - defined defaults are not available and are passed in when a component needs to be referenced.Copy the code
  • Component naming rules?

At the beginning of the component design, it should have the name of the uncoupled business

A generic or possible future gm, to have a relatively reasonable, such as Search and List, try not to appear and coupling of deep business term, a common component has nothing to do with the business, only associated with its abstract component We at the beginning of the design components, we should have this idea, wait for real utility components to spare, And then you have to change your name? Libraries are usually intended for use by a wide range of developers, so when designing components, we can lower the standards so that they are common throughout your APP firstCopy the code

Fine-grained considerations for component partitioning (degree of extraction)

Component design rules clearly state that we should follow the single responsibility principle, which brings with it the problem of excessive abstraction (componentization) discussed above. Let’s talk about this in the context of the specific business

To implement the badge component, it has two parts

  • button
  • Top right tip (red dot /icon)

Both are consistent with a single responsibility and can be separated into a separate component, but usually don’t

Because the same app style will be uniform, there is no other application scenario, as mentioned above, before pulling out components, ask yourself why and input/output ratio, there is no absolute ruleCopy the code

tips

Single responsibility components should be built on the basis of reusability. For non-reusable single responsibility components, we can only serve as internal components of independent components

A used-car website exemplifies its fine-grained approach

Think about how you would design it if you had to… That’s how I designed it

index.js(react)

<div className="select-brand-box" onTouchStart={touchStartHandler} onTouchMove={touchMoveHandler} onTouchEnd={touchEndHandler.bind(this, touchEndCallback)}>
     <NavBar></NavBar>
     <Brand key="brands-list"{... brandsProps} /> <Series key="series-list"{... seriesProps} > </div>export default BrandHoc(index);

Copy the code

Brand.js(react)

<div className="brand-box">
    <div className="brand-wrap" ref="brandWrap">
        <p className="brands-title hot-brands-title"> < span style = "box-sizing: border-box; color: RGB (74, 74, 74); line-height: 22px; font-size: 14px! Important; white-space: inherit! Important;" isHideStar && <UnlimitType {... unlimitProps} />} <AllBrands {... brandsProps} /> </div> <AsideLetter {... asideProps} /> {showPop ? <PopTips key="pop-tips" tip={currentLetter} /> : null}
    {showBrandLoading ? <Loading /> : null}
</div>
            

Copy the code

FlexLayout.js(react)

This example covers almost all of the rules

  • First of all, the design of components is divided according to the business, so the right letter navigation (AsideLetter) is not in the outermost container components, otherwise the communication problem will take up part of the space, in fact, this is a solution
  • The entry component is the container component, in fact think of it as a rule, a carrier of business logic
  • With the exception of the container components, all the components are extracted for common use, and there are many similar scenarios for the used car platform

  • Selling car platform similar graphics and graphics mixed row and different forms, a wide range of application scenarios, smoke! The UI differences are contained within the component. Refer to FlexLayout.js for default props
  • How to solve communication difficulties caused by too many extractable components (business driven)? That means you need to add a container component that can manage the state. In the example above, Brand and Series are container components that manage the size of the subcomponents
  • Fine-grained considerations, consider the ratio of effort to output
<p className="brands-title hot-brands-title"Word-wrap: break-word! Important; "> < p style =" max-width: 100%Copy the code
  • The process of component withdrawal is the process of infinite proximity to the stateless component

Consideration of generality

A component’s shape (UI) is always variable, but its behavior (logic) is fixed, so one of the secrets of a generic component is to give the developer control of the DOM structure, and the component is responsible for only the behavior and the most basic DOM structure

This is a conspicuous chestnut

One day, you get a demand like this

Happy, simple, three five divided by two

Suddenly one day there is such a need

emm.. Can be customized? The previous select is no longer available. What can I do? Do you want to change the last one or write another one? Once this happens, it proves that the previous component needs to be redesigned

The key to achieving universal design is to relinquish control of the Dom

The question is, with so many customizations, will the component be difficult to use?

Generic design specifies default values while leaving Dom structure decisions to the developer

Here’s a freshly baked (vue)🌰

The List component

Parent component 🌰(vue) and slot

Template (pseudocode) <template> <List :data="tableData[item.type]" :loading="loading" @loadMore="loadMore" :noMore="noMore">
    <a v-if="item.type == 0" slot="listOption" slot-scope="childScope" class="edit-btn" @click="edit(childScope.data)" v-bind:key="childScope.data.id">{{Status[childScope.data.status]['text'}}</a> </List> </template>export const Status = {
  //....
  1: {
    label: 'draft'.type: ' ',
    text: 'edit',
    class: 'note'}} / /...Copy the code

There’s another chestnut (vue)

  • Dialog only takes care of the basic logic, handing over control to the business. What does your business need to do in the container component (business logic layer)

Can’t help but point to the opposite of rock-solid businesses

The difficulty of using is a two-fold problem

  1. Refusing to hand over control
  2. No API documentation

All of the business logic and scenarios are contained within the components, and the outside world is controlled only by variables. The intention is good, but as the business grows and the components get bigger, the developer becomes more and more unable to handle them

Just at this stage UI revision, our workload from only change the style directly into over again, and there is no detailed documentation, the workload instantly turned N times 😭 baby heart bitter baby do not say

Use design patterns

In fact, at first, I didn’t apply design patterns specifically. It was purely business driven. You’ve seen that

Once the logic becomes more and more coupled to the business, the components will naturally have no commonality, even if we don’t consider commonality.

Let’s think about whether it’s better to write it this way

Config (pseudo code)export const Status = {
  4: {
    label: 'Partial storage'.type: ' ',
    text: 'look at'}} template (vue) <a v-if="item.type == 0" slot="listOption" slot-scope="childScope" class="edit-btn" @click="edit(childScope.data)" v-bind:key="childScope.data.id">{{Status[childScope.data.status]['text']}}</a>

Copy the code

There is no design pattern in the world, and more people write it, it will stand out from the rest and be remembered by history! Not only that, a part of the seemingly complex business if the configuration items are properly designed, you can save a lot of JS

Some feeling

The underlying business support system like rock requires lots of lists, queries, edits, details, etc. I usually spend about 30 seconds building a shelf like, but not limited to, the one below

  • Index: module entry (assumes container responsibilities)
  • API: API of the whole business
  • Components A collection of business components
1. The Form is usually referenced by add.vue and edit.vue. 2. The things that you don't see in other businesses are basically abstractions to common: breadcrumb navigation, unroll, and so onCopy the code
  • Various configurations of the LIBS page

Concrete embodiment (rock just reconstructed module)

Purchasing module structure diagram

form

edit

No matter how many states there are, they are maintained only at the Edit layer

The reason for doing this

  • Components in Components are only temporary and can be upgraded to generic components, so be careful to name them in a uniform way to prevent business coupling
  • Bug can be traced, data problems I must be from the outside of the investigation, style problems from the investigation, locating the problem fast
  • Struggle with repetitive code, maintain a compulsive mentality to organize each module, form their own coding style, and then the team style can be unified

conclusion

  • When it comes to component design, it’s important to be well prepared, but in the real world, tangible results are the most important thing, and component design should not be overdesigned or stagnant. Do it when you need to do it, and change it when you find it bad
  • In your spare time, think about the less-than-ideal early code, which can be used as a basis for moving forward
  • Technology is changing, but the core of componentization has not changed. The goal is still to reuse, decouple, encapsulate and abstract the API design as close to the original as possible, and ultimately serve the development, improve efficiency and reduce error rate
  • Componentization is a layering of implementations, a way to combine code more efficiently
  • Componentization is the reorganization and optimization of resources, so as to make the project resource management more reasonable, convenient to remove and insert, convenient to integrate, convenient to delete, convenient to rejoin after deletion
  • This idea of simplifying is embodied in the back-end development as microservices, and in the front-end development as componentization
  • Componentization is good for unit test and self test efficiency and is good for refactoring
  • New recruits can directly assign components for development and testing, instead of having to be familiar with the whole project. New recruits can quickly familiarize themselves with the project and understand the development specifications from the development of one component
  • Your direct responsibility may be to write the code, but your ultimate goal is to create the product

One last word

There is no end to componentization, day day up

Refer to the link

  • Engineering.carsguide.com.au/front-end-c…
  • Segmentfault.com/a/119000000…
  • Juejin. Cn/post / 684490…
  • Medium.com/merrickchri…
  • www.alloyteam.com/2015/11/we-…