This time I will bring you a detailed explanation of the use of slot slots in Vue. What are the precautions when using slot slots in Vue. The following is a practical case, let's take a look.
The following is an example to briefly explain the working principle of slots
The template of the dx-li subcomponent is as follows:
The passed slot content 'hello juejin!' will be compiled into a child node of the dx-li sub-component VNode node.
Render the dx-li subcomponent, in which the render function of the subcomponent:
module.exports={ render:function (){ var _vm=this; var _h=_vm.$createElement; var _c=_vm._self._c||_h; // 其中_vm._v 函数为renderSlot函数 return _c('li', {staticClass: "dx-li" }, [_vm._t("default", [_vm._v("你好 掘金!")])], 2 ) }, staticRenderFns: [] }
During the initialization of the dx-li subcomponent vue instance, the initRender function will be called:
function initRender (vm) { ... // 其中_renderChildren数组,存储为 'hello juejin!'的VNode节点;renderContext一般为父组件Vue实例 这里为dx-ul组件实例 vm.$slots = resolveSlots(options._renderChildren, renderContext); ... }
The resolveSlots function is:
/** * 主要作用是将children VNodes转化成一个slots对象. */ export function resolveSlots ( children: ?Array<vnode>, context: ?Component ): { [key: string]: Array<vnode> } { const slots = {} // 判断是否有children,即是否有插槽VNode if (!children) { return slots } // 遍历父组件节点的孩子节点 for (let i = 0, l = children.length; i * 编译成span的VNode节点data = {attrs:{slot: "abc"}, slot: "abc"},所以这里删除该节点attrs的slot */ if (data && data.attrs && data.attrs.slot) { delete data.attrs.slot } /* 判断是否为具名插槽,如果为具名插槽,还需要子组件/函数子组件渲染上下文一致。主要作用: *当需要向子组件的子组件传递具名插槽时,不会保持插槽的名字。 * 举个栗子: * child组件template: * <p> * </p> <p><slot></slot></p> * <p><slot></slot></p> * * parent组件template: * <child><slot></slot></child> * main组件template: * <parent><span>foo</span></parent> * 此时main渲染的结果: * <p> * </p> <p><span>foo</span></p> <p></p> * */ if ((child.context === context || child.fnContext === context) && data && data.slot != null ) { const name = data.slot const slot = (slots[name] || (slots[name] = [])) // 这里处理父组件采用template形式的插槽 if (child.tag === 'template') { slot.push.apply(slot, child.children || []) } else { slot.push(child) } } else { // 返回匿名default插槽VNode数组 (slots.default || (slots.default = [])).push(child) } } // 忽略仅仅包含whitespace的插槽 for (const name in slots) { if (slots[name].every(isWhitespace)) { delete slots[name] } } return slots }</vnode></vnode>
Then when the dx-li component is mounted, the dx-li component render function will be called. In the process, the renderSlot function will be called:
export function renderSlot ( name: string, // 子组件中slot的name,匿名default fallback: ?Array<vnode>, // 子组件插槽中默认内容VNode数组,如果没有插槽内容,则显示该内容 props: ?Object, // 子组件传递到插槽的props bindObject: ?Object // 针对<slot></slot> obj必须是一个对象 ): ?Array<vnode> { // 判断父组件是否传递作用域插槽 const scopedSlotFn = this.$scopedSlots[name] let nodes if (scopedSlotFn) { // scoped slot props = props || {} if (bindObject) { if (process.env.NODE_ENV !== 'production' && !isObject(bindObject)) { warn( 'slot v-bind without argument expects an Object', this ) } props = extend(extend({}, bindObject), props) } // 传入props生成相应的VNode nodes = scopedSlotFn(props) || fallback } else { // 如果父组件没有传递作用域插槽 const slotNodes = this.$slots[name] // warn duplicate slot usage if (slotNodes) { if (process.env.NODE_ENV !== 'production' && slotNodes._rendered) { warn( `Duplicate presence of slot "${name}" found in the same render tree ` + `- this will likely cause render errors.`, this ) } // 设置父组件传递插槽的VNode._rendered,用于后面判断是否有重名slot slotNodes._rendered = true } // 如果没有传入插槽,则为默认插槽内容VNode nodes = slotNodes || fallback } // 如果还需要向子组件的子组件传递slot /*举个栗子: * Bar组件: <p><slot></slot></p> * Foo组件:<p><bar><slot></slot></bar></p> * main组件:<p><foo>hello</foo></p> * 最终渲染:<p></p> <p>hello</p> */ const target = props && props.slot if (target) { return this.$createElement('template', { slot: target }, nodes) } else { return nodes } }</vnode></vnode>
scoped slots understanding
The template of the dx-li subcomponent is as follows:
The _vm._u function:
function resolveScopedSlots ( fns, // 为一个对象数组,见上文scopedSlots res ) { res = res || {}; for (var i = 0; i <p style="text-align: left;">The subsequent rendering process of the subcomponent is similar to slots. The principle of scoped slots is basically the same as that of slots. The difference is that when compiling the parent component template, a function that returns a VNode will be generated. When the child component matches the scope slot function passed by the parent component, the function is called to generate the corresponding VNode. </p><p style="text-align: left;"><span style="color: #ff0000"><strong>Summary</strong></span></p><p style="text-align: left;">In fact, the principle of slots/scoped slots is very simple. We only need to understand that when vue renders components, it is based on VNode Renders actual DOM elements. </p><p style="text-align: left;">Slots are slot VNodes generated by compiling parent components. When rendering sub-components, they are placed in the corresponding sub-component rendering VNode tree. </p><p style="text-align: left;">scoped slots compiles the slot content in the parent component into a function. When rendering the sub-component, pass in the sub-component props and generate the corresponding VNode. Finally, the subcomponent returns the VNode node tree according to the component render function, and updates to render the real DOM elements. At the same time, it can be seen that passing slots across components is also possible, but care must be taken to pass named slots. </p><p> I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website! </p><p>Recommended reading: </p><p><a href="http://www.php.cn/js-tutorial-393590.html" target="_blank">Detailed explanation of the use of the slot socket of the vue component</a><br></p><p><a href="http://www.php.cn/js-tutorial-393588.html" target="_blank">Detailed explanation of the use of JS origin policy for cross-domain access</a></p>
The above is the detailed content of Detailed explanation of slot usage in Vue. For more information, please follow other related articles on the PHP Chinese website!

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Atom editor mac version download
The most popular open source editor

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver CS6
Visual web development tools

SublimeText3 Chinese version
Chinese version, very easy to use

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software
