preface
I am currently working on my own component library with Vue+TypeScript. I refer to the source code of element and iView (😂). Discover some commonly used features behind, often complex implementations. I decided to write a series of articles on the principles behind these components. Today’s second installment takes you through the implementation of Grid components.
API design
It is customary to start by looking at the interface design of the iView and Element components. The grid component is divided into two main parts, Row and Col.
The Row components Props | explain |
---|---|
gutter | The spacing between each column, specified in pixels. |
Col component Props | explain |
---|---|
span | The width of a column, usually a number between 1 and 24 |
offset | Specifies the offset of the column |
Row
Template design
Nothing to say, just use the slot slot to replace the inserted Col component.
Props.gutter
Props. Gutter is the span for each column. This would be the Col attribute for each column, but for convenience it is not possible to set the span attribute for each Col component. So it’s all set on Row, so how do we set properties on Row to Col?
Let’s start by defining two utility functions as follows:
FindChildsComponentByLevel,The named child component of the specified component is found, and the level of the lookup can be specified. FindChildsComponentByLevel method is the main use of the component instanceOptions. The name attribute.
The $children property represents the immediate children of the current instance.
$options.name represents the name property specified when the component is initialized.
Use recursion inside utility functions to find subcomponents with specific names down the hierarchy.
FindChildsComponentByFirstLevel method is the encapsulation of findChildsComponentByLevel method, used to locate the first straton components.
We define the handleGutterChange method inside the component and use watch to monitor the gutter property. Every time the gutter property changes, the handleGutterChange method updates the gutter property to the col component.
Col
Template design
It’s relatively simple and I won’t repeat it here
Data.gutter
In the Row component we update the gutter property to the Row component by looking for $children.
Inside the Row component, listen to the cache calculate the gutter attribute using the calculated attribute. Translate the gutter to the gutter and update it to the Row component’s :style property. Implement gutter function.
offset, span
The implementation of offset and SPAN is implemented solely by CSS. Use loop recursion of less
Form row-span-1, row-span-2, row-span-3, row-span-4… The CSS class. Then use the built-in percentage function less to dynamically generate the width property of the CSS.
Finally, we need to dynamically generate the col CSS class name by calculating the properties, and row-span-1, row-span-2, row-span-3… Corresponding to
reference
- Iview source
- Element source