Vue.js- functional components

Learning notes:Functional component

Functional component

Vue provided onefunctionalIs set totrueYou can make components stateless and instanced, that is, withoutdataAndthisContext. Use this wayrenderFunctions that return virtual nodes can be rendered more easily because the functional component is only a function and the rendering cost is much lower.

When using a functionalized component, the Render function provides the second argumentcontextTo provide a temporary context. Required by componentdatapropslotschildrenparentIs passed through this context. such asthis.levelTo rewrite ascontext.props.level,this.$slots.defaultChange tocontext.children.

Use functional components to show a scenario of intelligently selecting different components according to data:

< pdata-height = “365” data-theme-id = “0” data-slug-hash = “mkrgm” data-default-tab = “html, result” data-user = “whjin” data-embedded-version = “2” data-pen-title = “vue-functional component-select component according to data” class=”codepen”>See the PenVue- Functionalized Component-Select Components Based on Databy whjin (@whjin) onCodePen.</p>
<script async src=” …; ></script>

Functionalized components are mainly applicable to the following two scenarios:

  1. Programmatically select one of a plurality of components.
  2. In willchildrenpropsdataOperate the subcomponents before passing them to them.


In order to make the Render function write and read better, Vue provides plug-insbabel-plugin-transform-vue-jsxTo support JSX syntax.

UsecreateElementCommon configuration:

<p data-height=”365″ data-theme-id=”0″ data-slug-hash=”Vdpwpz” data-default-tab=”js” data-user=”whjin” data-embed-version=”2″ data-pen-title=”Vue-createElement” class=”codepen”>See the PenVue-createElementby whjin (@whjin) onCodePen.</p>
<script async src=” …; ></script>

JSX writing:

<p data-height=”300″ data-theme-id=”0″ data-slug-hash=”eKvYvm” data-default-tab=”js” data-user=”whjin” data-embed-version=”2″ data-pen-title=”Vue-JSX” class=”codepen”>See the PenVue-JSXby whjin (@whjin) onCodePen.</p>
<script async src=” …; ></script>

Actual Combat: Using Render Function to Develop Sortable Table Components

All contents (header and row data) of the table component consist of twopropComposition:columnsAnddata. Both are arrays,columnsUsed to describe the information of each column, and rendered in the header<head>, you can specify whether a column needs sorting;dataWhen each row of data, bycolumnsDecide the order of the columns in each row.

In order for the sortedcolumnsAnddataDoes not affect the original data, tov-tableComponent ofdataOption to add two corresponding data, all operations of the component will be completed on the two data, without any processing of the original data.

columnsEach item of is an object, wheretitleAndkeyThe field is required to identify the header title of this column.keyCorrespondence ofdataThe field name of the contents of the column in.sortableIs an optional field, if the value istrue, indicating that the column needs sorting.

v-talbeComponent ofprop:columnsAnddataThe data of has been transferred from the parent.v-tableInstead of using them directly, use themdataOf optionscurrentColumnsAndcurrentData. So inv-tableDuring initialization, thecolumnsAnddataAssign tocurrentColumnsAndcurrentData. Inv-tableThemethodsOption to define two methods for copying, and in themountedCalled within the hook.

map()Is a method of JavaScript array, reconstructing a new array according to the function passed in.

Sort by ascending order (asc) and descending (desc) two, and at the same time can only sort one column of data, mutually exclusive with other columns, in order to identify the sorting status of the current column, inmapWhen adding data to columns, one is added to each column by default_sortTypeAnd is assigned tonormalA that represents the default sort (that is, no sort).

After sorting,currentDataThe order of each item may change, so givecurrentColumnsAndcurrentDataEach data of is added_indexField that represents the index of the current data in the original data.

render(h) {
    var ths = [],
        trs = [];
    return h('table', [
        h('thead', [
            h('tr', ths)
        h('tbody', trs)

HerehexactlycreateElement, just changed the name.

Table topictrsIs a two-dimensional array, data bycurrentColumnsAndcurrentDataComposition.

First, all rows are traversed, then each column is traversed within each row, and finally the topic content node is combined.trs.

Ifcol.sortableNo definition, or value isfalse, just put directlycol.titleRender it, otherwise in addition to renderingtitle, also added two<a>Element to implement ascending and descending operations.

Sorting with JavaScript arrayssort()Method, the reason for returning here1Or-1Instead of returning directlya[key]<b[key], that is to saytrueOrfalseBecause in some browser pairssort()The treatment of different, and1And-1Can be compatible.

Before sorting, reset the sorting status of all columns tonormal, and then set the sort status of the current column (ascOrdescFor those that use render<a>elementaryclassNameon, followed by CSS to highlight the sorting status of the current column.

After rendering the table, the parent modified itdataData, such as additions or deletions,v-tableThecurrentDataIt should also be updated. If a column already has a sort status, the sort should be processed directly after the update.

Through traversalcurrentColumnsTo find out whether it has been sorted by a certain column, and if so, to sort the updated data according to the current sorting status.

< pdata-height = “365” data-theme-id = “0” data-slug-hash = “xymmjr” data-default-tab = “html, result” data-user = “whjin” data-embedded-version = “2” data-pen-title = “vue-sortable table component” class=”codepen”>See the PenVue- sortable table componentby whjin (@whjin) onCodePen.</p>
<script async src=” …; ></script>

Actual Combat: Message List

To publish a message, the required data include nickname and message content. The publishing operation should be at the root instanceappComplete in. The data of the message list is also fromappGet.

arraylistStored all the message content, through the functionhandleSendtolistAdd a message data, add intotexrareaThe text box is empty.

Node Usage within Render Functionv-model: dynamic bindingvalueAnd listeninputEvent, the input content through$emit('input')Dispatched to the parent component.

List datalistWhen empty, render a “list is empty” message node; When not empty, eachlist-itemWinning includes nickname, message content and reply button 3 sub-nodes.

this.list.forEachEquivalent totemplateFrom insidev-forCommand, traverse out each message. handlehandleReplyDispatch an event directly to the parent componentreply, parent component (appAfter receiving, the currentlist-itemThe nickname of the extraction, and set tov-textareaInside.

< pdata-height = “365” data-theme-id = “0” data-slug-hash = “zrkgrr” data-default-tab = “html, result” data-user = “whjin” data-embedded-version = “2” data-pen-title = “vue-message list” class=”codepen”>See the PenVue- message listby whjin (@whjin) onCodePen.</p>
<script async src=” …; ></script>