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

Solution to the problem that Centos8 cannot install docker

Problem [root@zh ~]# [root@zh ~]# [root@zh ~]# yu...

Realization of real-time file synchronization between Linux servers

Usage scenarios For existing servers A and B, if ...

Detailed explanation of VUE Token's invalidation process

Table of contents Target Thought Analysis Code la...

IIS7 IIS8 http automatically jumps to HTTPS (port 80 jumps to port 443)

IIS7 needs to confirm whether the "URL REWRI...

WeChat applet records user movement trajectory

Table of contents Add Configuration json configur...

Analysis of MySQL's method of exporting to Excel

This article describes how to use MySQL to export...

Example of setting up a whitelist in Nginx using the geo module

Original configuration: http { ...... limit_conn_...

Detailed explanation of firewall rule settings and commands (whitelist settings)

1. Set firewall rules Example 1: Expose port 8080...

Windows platform configuration 5.7 version + MySQL database service

Includes the process of initializing the root use...

Detailed explanation of the role of brackets in AngularJS

1. The role of brackets 1.1 Square brackets [ ] W...

Summary of MySQL usage specifications

1. InnoDB storage engine must be used It has bett...

How to add rounded borders to div elements

As shown below: CSS CodeCopy content to clipboard...

SQL query for users who have logged in for at least n consecutive days

Take 3 consecutive days as an example, using the ...