Learn a vue every day
Functional component features:
- No state is managed
- It’s not listening for any state passed to it
- There is no lifecycle method
- It just receives some letters of prop
We mark such a component as functional:
- Stateless == Unresponsive data
- No instance == No this context
Advantages of functional components:
- Rendering overhead is low because functional components are just functions;
Basic writing method of functional component:
{functional: true, // Props are optional Props: {//... Render: function (createElement, context) {//... }}Copy the code
Everything the component needs is passed through the context parameter, which is an object containing the following fields:
- Props: provides all prop objects
- Children: An array of VNode children
- Slots: a function that returns an object containing all slots
- ScoptedSlots :(2.6.0) an object that exposes the passed scoped slots as well as normal slots as functions
- Data: Passes the entire data object of a component as the second argument to createElement
- Parent: A reference to the parent component
- An event listener object that contains all parent components of the current component ancestor is an alias for data.on
- If the inject option is used, the object contains: attributes that should be injected;
Usage scenario 1: Wrapping components
-
Programmatically select one of several components to render for you;
-
Operate on children, props, and data before passing them to child components; Here is an example of a smart-list component that renders more specific components based on the value of the prop passed in:
var EmptyList = { /* ... */ } var TableList = { /* ... */ } var OrderedList = { /* ... */ } var UnorderedList = { /* ... */ } Vue.component('smart-list', { functional: true, props: { items: { type: Array, required: true }, isOrdered: Boolean }, render: function (createElement, context) { function appropriateListComponent () { var items = context.props.items if (items.length === 0) return EmptyList if (typeof items[0] === 'object') return TableList if (context.props.isOrdered) return OrderedList return UnorderedList } return createElement( appropriateListComponent(), context.data, context.children ) } }) Copy the code
A comparison between slots() and children
Analysis:
It is obvious from the literal meaning:
-
Children, which can get all the children of the current component node;
-
The slots() function returns all slot objects; For example:
<my-functional-component> <p v-slot:foo> first </p> <p>second</p> </my-functional-component> Copy the code
For the above example components:
- Children will give you two paragraph tags;
- Slots ().default only passes the second anonymous paragraph tag
- Slots ().foo passes the first named paragraph tag
Conclusion:
- You can choose to use slots() to make the component aware of a slot mechanism, or you can simply pass children to another component
Refer to the website