In-depth understanding of slot-scope in Vue (suitable for beginners)

In-depth understanding of slot-scope in Vue (suitable for beginners)

There are already many articles about slot-scope on Baidu, but I feel that they are all from people who didn’t learn it well before and are learning it again. They all use .Vue files, which I think is not suitable for beginners, so I will write an article suitable for beginners.

First throw routine:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Components distributing content through slots</title>
    <script src="your vue address, please download the latest version"></script>
    <script>
        Vue.component("test-slot",{
           // Slots allow for default content template:
               `<div>
                    Error!
                    <slot></slot>
                </div>
               `,
            data:function () {
                return {
                    name:"perry"
                }
            }
        });
    // Named slot Vue.component("slot-name",{
           template:
               `<div>
                      <header>
                            <slot name="header"></slot>
                      </header>
                     <main>
                        <slot ></slot>
                     </main>
                     <footer>
                        <slot name="footer"></slot>
                     </footer>
 
                </div>
               `
        });
        
    // Scope slot Vue.component("todo-list",{
            inheritAttrs:false,
            props:{
                todos:[Array,Object]
            },
            template:
            `<ul>
                <li v-for="todo in todos" :key="todo.id" style="display: block;" >
                    <slot :data="todo">{{todo.text}}</slot>
                </li>
             </ul>
            `
        });
                
    </script>
    
    <style>
        li{
            list-style: none;
            display: inline-block;
            font-size: 25px;
        }
    </style>
</head>
<body>
    <div id="app">
        <!--1. Slot content slot can receive any content, code, including components-->
        <test-slot>Something bad happened. Who are you? Do I know you?</test-slot>
        <test-slot>
            Something bad happened.
            <!--Variables are allowed, but they must be in this scope to be effective. Here, the value of name will be "叉道口"-->
            <h3>Title {{name}}</h3>
            <img src="img/flower.jfif" alt="Image cannot be displayed">
        
        </test-slot>
        <!--2. The named slot slo has a special attribute name, which can make the slot named-->
        <slot-name>
            <h3>Encourage learning</h3>
            <p>If you don't work hard when you are young, you will regret it when you are old</p>
            <p>Time flies like an arrow</p>
            <template slot="header">
                <ul>
                    <li>Home</li>
                    <li>About time</li>
                    <li>About life</li>
                    <li>About the future</li>
                </ul>
            </template>
            <p>Hello</p>
            <p slot="footer">
                <p>End</p>
                <p>粤ICP备6545646456415</p>
            </p>
        </slot-name>
        
        <!--Use scoped slots, implemented via slot-scope -->
        <todo-list :todos="todos">
            <template slot-scope="slotProps">
                <span v-if="slotProps.data.isTrue">√</span>
                {{slotProps.data.text}}
            </template>
        </todo-list>
        
        <!--Use ES2015 structure syntax-->
        <todo-list :todos="todos">
            <template slot-scope="{data}">
                <span v-if="data.isTrue">√</span>
                {{data.text}}
            </template>
        </todo-list>        
    </div>
        
    <script>
        new Vue({
            el:"#app",
            data:{
                name:"Crossroad",
                todos:
                    {text:"A",id:1,isTrue:true},
                    {text:"B",id:2,isTrue:true},
                    {text:"C",id:3,isTrue:false},
                    {text:"D",id:4,isTrue:true},
                ],
                // slotProps: ""
            }
        })
        
    </script>
</body>
</html>

The example also describes ordinary slots and named slots, which I will not discuss here. I will only talk about scoped slots. First of all, let's start with the name "scope slot". Originally, your parent component template cannot use the data in the child component template. There is a special emphasis in the official website: everything in the parent component template will be compiled in the parent scope; everything in the child component template will be compiled in the child scope. This sentence is actually quite difficult to understand. Let's take an example to understand.

<test-slot>

          Something bad happened.

         <!--Variables are allowed, but they must be in this scope to be effective. Here, the value of name will be "叉道口"-->

           <h3>Title {{name}}</h3>

           <img src="img/flower.jfif" alt="Image cannot be displayed">

</test-slot>

This is my example above, which means that the name here must be in the current component, and cannot be the data inside the test-slot component. This is its scope limitation. The name data belongs to the scope of the parent component, so it can only be the data of the parent component. However, the emergence of slot-scope enables the parent component to call the data inside the child component, and the data of the child component is passed to the parent component through the slot-scope attribute

// Scope slot Vue.component("todo-list",{
        inheritAttrs:false,
        props:{
            todos:[Array,Object]
        },
        template:
        `<ul>
            <li v-for="todo in todos" :key="todo.id" style="display: block;" >
                  //Here: data="todo" means that the child component todo data is passed to the parent component<slot :data="todo">{{todo.text}}</slot>//todo.text is the default value, the parent component will overwrite it</li>
         </ul>
        `
    });
<!--Use scoped slots, implemented via slot-scope -->
<todo-list :todos="todos">
    <template slot-scope="slotProps">
        <span v-if="slotProps.data.isTrue">√</span>
        {{slotProps.data.text}}
    </template>
</todo-list>

This is how it is used. The data named data with a value of todo passed from the child component will be received by slot-scope. It should be noted that slot-scope receives an object, named slotProps here, which means that the data you pass will be used as a property of slotProps, so slotProps.data is required to call data. As mentioned before, the value of data is todo. What is todo? Todo is traversed from todos, so it is an object.

new Vue({
    el:"#app",
    data:{
        name:"Crossroad",
        todos:
            {text:"A",id:1,isTrue:true},
            {text:"B",id:2,isTrue:true},
            {text:"C",id:3,isTrue:false},
            {text:"D",id:4,isTrue:true},
        ],
        // slotProps: ""
    }
});

We have understood the slot-scope feature, so what are its application scenarios? We can imagine that someone has written a component that has been encapsulated, but he thinks that the display style of the data should be defined by the user. Just like above, we hope that the style of the list is defined by the user, for example, I added a √ sign. At the beginning, we pass in the initial data, but the data must be processed by the subcomponent. The person who wrote the component must want to display the processed data. At this time, slot-scope is extremely important.

Summarize

This concludes this article on in-depth understanding of slot-scope in Vue. For more information on understanding Vue slot-scope, please search previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • The problem of Vue+tsx using slot is not replaced
  • About VUE's compilation scope and slot scope slot issues
  • Detailed analysis of the usage and application scenarios of slots in Vue
  • Solve the problem of secondary encapsulation and slots rendering of ant design vue table a-table
  • Vue slot_Special features slot, slot-scope and directive v-slot description
  • Detailed explanation of the usage of scoped slots in Vue.js slots

<<:  Detailed example of creating and deleting tables in MySQL

>>:  A detailed account of the process of climbing a pit of Docker deployment service

Recommend

How to use Node.js to determine whether a png image has transparent pixels

background PNG images take up more storage space ...

Summary of common MySQL commands

Set change mysqlroot password Enter the MySQL dat...

Vue achieves the top effect through v-show

html <div class="totop" v-show="...

Vue implements verification whether the username is available

This article example shares the specific code of ...

HTML code text box limit input text box becomes gray limit text box input

Method 1: Set the readonly attribute to true. INPU...

Zen HTML Elements Friends who use zen coding can collect it

html ¶ <html></html> html:xml ¶ <h...

The background color or image inside the div container grows as it grows

Copy code The code is as follows: height:auto !im...

Some tips on using the HTML title attribute correctly

If you want to hide content from users of phones, ...

How to increase HTML page loading speed

(1) Reduce HTTP requests. (Merge resource files a...

js to upload pictures to the server

This article example shares the specific code of ...

Set the width of the table to be fixed so that it does not change with the text

After setting the table width in the page to width...

Detailed explanation of Vue custom instructions and their use

Table of contents 1. What is a directive? Some co...

Ubuntu 20.04 connects to wifi (2 methods)

I recently installed Ubuntu 20.04 and found that ...

Example of automatic stop effect after text scrolling

The effect is very simple, just copy the following...