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

Discussion on more reasonable creation rules for MySQL string indexes

Preface Regarding the use of MySQL indexes, we ha...

How to ensure that every page of WeChat Mini Program is logged in

Table of contents status quo Solution Further sol...

Let’s talk about the symbol data type in ES6 in detail

Table of contents Symbol Data Type The reason why...

How to change the terminal to a beautiful command line prompt in Ubuntu 18

I reinstalled VMware and Ubuntu, but the command ...

Detailed examples of converting rows to columns and columns to rows in MySQL

mysql row to column, column to row The sentence i...

Detailed explanation of Linux Namespace User

User namespace is a new namespace added in Linux ...

Use of MySQL truncate table statement

The Truncate table statement is used to delete/tr...

Detailed tutorial on installing Tomcat9 windows service

1. Preparation 1.1 Download the tomcat compressed...

...

VMware Workstation installation Linux system

From getting started to becoming a novice, the Li...

JavaScript to make the picture move with the mouse

This article shares the specific code of JavaScri...

Detailed explanation of group by and having in MySQL

The GROUP BY syntax can group and count the query...