Home Web Front-end Vue.js Detailed explanation of scope slots in Vue.js

Detailed explanation of scope slots in Vue.js

Sep 30, 2020 pm 05:37 PM
vue.js

Detailed explanation of scope slots in Vue.js

Scope slots are a useful feature of Vue.js that can make components more versatile and reusable. The only problem is they're hard to understand! Trying to wrap your head around parent and child ranges is like solving a tricky math equation.

When you can't understand something easily, a good approach is to try to use it to solve the problem. In this article, I'll demonstrate how to use scoped slots to build a reusable list component.

Detailed explanation of scope slots in Vue.js

Basic components

The component we are going to build is called my-list and it shows a lot thing. What's special about this feature is that you can customize how the list items are rendered each time the component is used.

Let's deal with the simplest use case first and get my-list to render a list: an array of geometry shape names and their number of sides.

app.js

Vue.component('my-list', {
  template: '#my-list',
  data() {
    return {
      title: 'Shapes',
      shapes: [ 
        { name: 'Square', sides: 4 }, 
        { name: 'Hexagon', sides: 6 }, 
        { name: 'Triangle', sides: 3 }
      ]
    };
  }
});

new Vue({
  el: '#app'
});
Copy after login

index.html

<div id="app">
  <my-list></my-list></div><script type="text/x-template" id="my-list">
  <div class="my-list">
    <div class="title">{{ title }}</div>
    <div class="list">
      <div class="list-item" v-for="shape in shapes">
        <div>{{ shape.name }} <small>({{ shape.sides }} sides)</small></div>
      </div>
    </div>
  </div>
</script>
Copy after login

After adding a little CSS, it will look like the following picture:

Detailed explanation of scope slots in Vue.js

Generalize my-list

Now, we want to make my-list versatile enough to render any kind of list. The second test case will be a list of colors, including a small sample showing the colors.

To do this, we must abstract any data specific to the shape list. Since items in a list may be structured differently, we will provide my-list with a slot so that the parent list can define how any particular list is displayed.

app.js

Vue.component(&#39;my-list&#39;, {
  template: &#39;#my-list&#39;,
  props: [ &#39;title&#39; ]
});
Copy after login

index.html

<script type="text/x-template" id="my-list">
  <div class="my-list">
    <div class="title">{{ title }}</div>
    <div class="list">
      <slot></slot>
    </div>
  </div>
</script>
Copy after login

Now let us create two instances of my-list component in the root instance to display our two test cases List:

app.js

new Vue({
  el: &#39;#app&#39;,
  data: {
    shapes: [ 
      { name: &#39;Square&#39;, sides: 4 }, 
      { name: &#39;Hexagon&#39;, sides: 6 }, 
      { name: &#39;Triangle&#39;, sides: 3 }
    ],
    colors: [
      { name: &#39;Yellow&#39;, hex: &#39;#F4D03F&#39;, },
      { name: &#39;Green&#39;, hex: &#39;#229954&#39; },
      { name: &#39;Purple&#39;, hex: &#39;#9B59B6&#39; }
    ]
  }
});
Copy after login
<div id="app">
  <my-list :title="Shapes">
    <div class="list-item" v-for="item in shapes">
      <div>{{ shape.name }} <small>({{ shape.sides }} sides)</small></div>
    </div>
  </my-list>
  <my-list :title="Colors">
    <div class="list-item" v-for="color in colors">
      <div>
        <div class="swatch" :style="{ background: color.hex }"></div>
        {{ color.name }}      </div>
    </div>
  </my-list></div>
Copy after login

Like this:

Detailed explanation of scope slots in Vue.js

##Surface components

The code we just created works fine, but the code isn't great. my-list is a component that displays a list by name. But we've abstracted away all the logic of rendering the list into the parent list. The component just wraps the list with some presentation markup.

##Considering that there are still duplicate codes in the two declarations of the component (for example

scoped slot

To achieve this, we will use scoped slots instead of regular slots. Scoped slots allow you to pass a template into the slot instead of passing the rendered element. It is called a "scoped" slot because although The template is rendered in the parent scope, but it has access to specific child data.

For example, with the role A component child component of a domain slot may look like this.

<div>
  <slot my-prop="Hello from child"></slot>
</div>
Copy after login
The parent component using this component will declare a template element in the slot. This template element will have an attribute scope that Specifies the alias object. Any props added to the slot (in the child template) are available as properties of the alias object.

<child>
  <template scope="props">
    <span>Hello from parent</span>
    <span>{{ props.my-prop }}</span>
  </template>
</child>
Copy after login

appears as:

<div>
  <span>Hello from parent</span>
  <span>Hello from child</span>
</div>
Copy after login

Using scope slots in my-list

Let us use the list array as Props are passed to my-list. We can then replace the slots with scoped slots. This way my-list can be responsible for iterating the list items, but the parent can still define how each list item should be displayed.

index.html

<div id="app">
  <my-list title="Shapes" :items="shapes">
    <!--template will go here-->
  </my-list>
  <my-list title="Colors" :items="colors">
    <!--template will go here-->
  </my-list>   
</div>
Copy after login
Now we get my-list to iterate over the items. In v -In the for loop, item is an alias of the current list item. We can create a slot and use v-bind="item" to bind the list item to the slot.


app.js

Vue.component(&#39;my-list&#39;, {
  template: &#39;#my-list&#39;,
  props: [ &#39;title&#39;, &#39;items&#39; ]
});
Copy after login

index.html

<script type="text/x-template" id="my-list">
  <div class="my-list">
    <div class="title">{{ title }}</div>
    <div class="list">
      <div v-for="item in items">
        <slot v-bind="item"></slot>
      </div>
    </div>
  </div>
</script>
Copy after login

NOTE: If you have not seen v-bind used without parameters before, this will Properties of the entire object are bound to the element. This is useful for scoped slots, since the object you are binding to often has arbitrary properties that now do not need to be specified by name.

现在我们将返回到根实例,并在my-list的slot中声明一个模板。首先查看形状列表,模板必须包含我们为其分配别名形状的scope属性。这个别名允许我们访问限定范围的道具。在模板内部,我们可以使用与以前完全相同的标记来显示形状列表项。

<my-list title="Shapes" :items="shapes">
  <template scope="shape">
    <div>{{ shape.name }} <small>({{ shape.sides }} sides)</small></div>
  </template>
</my-list>
Copy after login

下面是完整的模板:

<div id="app">
  <my-list title="Shapes" :items="shapes">
    <template scope="shape">
      <div>{{ shape.name }} <small>({{ shape.sides }} sides)</small></div>
    </template>
  </my-list>
  <my-list title="Colors" :items="colors">
    <template scope="color">
      <div>
        <div class="swatch" :style="{ background: color.hex }"></div>
        {{ color.name }}
      </div>
    </template>
  </my-list>   
</div>
Copy after login

结论

尽管这种方法和以前一样有很多标记,但它将公共功能委托给了组件,从而实现了更健壮的设计。

以下是完整代码的代码页:

https://codepen.io/anthonygore/pen/zExPZX

相关推荐:

2020年前端vue面试题大汇总(附答案)

vue教程推荐:2020最新的5个vue.js视频教程精选

更多编程相关知识,请访问:编程入门!!

The above is the detailed content of Detailed explanation of scope slots in Vue.js. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

In-depth discussion of how vite parses .env files In-depth discussion of how vite parses .env files Jan 24, 2023 am 05:30 AM

When using the Vue framework to develop front-end projects, we will deploy multiple environments when deploying. Often the interface domain names called by development, testing and online environments are different. How can we make the distinction? That is using environment variables and patterns.

What is the difference between componentization and modularization in vue What is the difference between componentization and modularization in vue Dec 15, 2022 pm 12:54 PM

The difference between componentization and modularization: Modularization is divided from the perspective of code logic; it facilitates code layered development and ensures that the functions of each functional module are consistent. Componentization is planning from the perspective of UI interface; componentization of the front end facilitates the reuse of UI components.

Detailed graphic explanation of how to integrate the Ace code editor in a Vue project Detailed graphic explanation of how to integrate the Ace code editor in a Vue project Apr 24, 2023 am 10:52 AM

Ace is an embeddable code editor written in JavaScript. It matches the functionality and performance of native editors like Sublime, Vim, and TextMate. It can be easily embedded into any web page and JavaScript application. Ace is maintained as the main editor for the Cloud9 IDE and is the successor to the Mozilla Skywriter (Bespin) project.

Practical combat: Develop a plug-in in vscode that supports vue files to jump to definitions Practical combat: Develop a plug-in in vscode that supports vue files to jump to definitions Nov 16, 2022 pm 08:43 PM

vscode itself supports Vue file components to jump to definitions, but the support is very weak. Under the configuration of vue-cli, we can write many flexible usages, which can improve our production efficiency. But it is these flexible writing methods that prevent the functions provided by vscode itself from supporting jumping to file definitions. In order to be compatible with these flexible writing methods and improve work efficiency, I wrote a vscode plug-in that supports Vue files to jump to definitions.

Let's talk in depth about reactive() in vue3 Let's talk in depth about reactive() in vue3 Jan 06, 2023 pm 09:21 PM

Foreword: In the development of vue3, reactive provides a method to implement responsive data. This is a frequently used API in daily development. In this article, the author will explore its internal operating mechanism.

Explore how to write unit tests in Vue3 Explore how to write unit tests in Vue3 Apr 25, 2023 pm 07:41 PM

Vue.js has become a very popular framework in front-end development today. As Vue.js continues to evolve, unit testing is becoming more and more important. Today we’ll explore how to write unit tests in Vue.js 3 and provide some best practices and common problems and solutions.

A simple comparison of JSX syntax and template syntax in Vue (analysis of advantages and disadvantages) A simple comparison of JSX syntax and template syntax in Vue (analysis of advantages and disadvantages) Mar 23, 2023 pm 07:53 PM

In Vue.js, developers can use two different syntaxes to create user interfaces: JSX syntax and template syntax. Both syntaxes have their own advantages and disadvantages. Let’s discuss their differences, advantages and disadvantages.

A brief analysis of how vue implements file slicing upload A brief analysis of how vue implements file slicing upload Mar 24, 2023 pm 07:40 PM

In the actual development project process, sometimes it is necessary to upload relatively large files, and then the upload will be relatively slow, so the background may require the front-end to upload file slices. It is very simple. For example, 1 A gigabyte file stream is cut into several small file streams, and then the interface is requested to deliver the small file streams respectively.

See all articles