Home Web Front-end JS Tutorial Using slots to pass data from parent component to child component in Vue.js

Using slots to pass data from parent component to child component in Vue.js

Sep 19, 2020 am 11:08 AM
vue.js vue slot Component communication

This article will introduce to you how to use Vue slots to pass data from parent components to child components in Vue.js. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.

Using slots to pass data from parent component to child component in Vue.js

#This article is suitable for developers of all stages (including beginners).

Before you begin

You will need the following on your computer:

  • Already Install Node.js version 10.x and above. You can verify the version by running the following command in Terminal/Command Prompt: node -v

  • Code Editor; Visual Studio Code

    # is recommended
  • ##The latest version of Vue, installed globally on your computer

  • Vue CLI 3.0 is installed on your computer. To do this, first uninstall the old CLI version:

  • npm uninstall -g vue-cli
    Copy after login
Then, install the new one:

npm install -g @ vue / cli
Copy after login

  • Download here

    Vue Getting Started Project

  • Unzip the downloaded project

  • Navigate to the unzipped file and run the command to keep all dependencies up to date :

  • npm install
    Copy after login

What are Vue slots?

Vue slot is a Vue template element created by the Vue team to provide a platform for template content distribution. It is an implementation of the Content Distribution API inspired by the draft Web Components specification. Using Vue slots, you can pass or distribute HTML code between various components in your project.

Why are Vue slots important?

Content distribution is important for many reasons, some of which have to do with structure. Using Vue slots, an HTML interface can be constructed (similar to TypeScript) which can then be used as a guide for building components via template injection. It is a very scalable and efficient solution for passing template code from one component to another.


Content positioning is another great use case for Vue slots. You simply create a template and then use another component or parent component to arrange the template the way you want it to appear in the user interface.

Slots vs. Props

#If you know about Vue slots, you might be wondering whether props and slots do the same thing. Well, the central idea of ​​these tools or platforms is to encourage reusability and efficiency of resources. With this in mind, slots and props are similar.

Props handles passing data objects between components, while slot handles passing template (html) content between components. However, scoped slots behave exactly like props; this will be clearly explained in this tutorial.

Vue Slot Syntax

For slots, your subcomponent acts as an interface or structure for how you want your content to be arranged. It might look like this:

<template>
  <div>
    <slot></slot>
  </div>
</template>
Copy after login

The parent component (where the HTML content to be injected into the child component resides) could look like this:

<Test>
   <h2>Hello World!</h2>
 </Test>
Copy after login

This combination will return a user interface that looks like this:

<template>
  <div>
    <h2>Hello World!</h2>
  </div>
</template>
Copy after login

Note how the slot itself serves as a guide for where and how content should be injected - this is the central idea.

Demo

If you have followed this article from the beginning, you will open

vue starter# in vs code ##project. To demonstrate the simple example in the syntax section, our parent component will be the app.vue file. Open the app.vue file and copy in this code block: <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class='brush:php;toolbar:false;'>&lt;template&gt; &lt;div id=&quot;app&quot;&gt; &lt;img alt=&quot;Vue logo&quot; src=&quot;./assets/logo.png&quot;&gt; &lt;Test&gt; &lt;h2&gt;Hello World!&lt;/h2&gt; &lt;/Test&gt; &lt;/div&gt; &lt;/template&gt; &lt;script&gt; import Test from &amp;#39;./components/Test.vue&amp;#39; export default { name: &amp;#39;app&amp;#39;, components: { Test } } &lt;/script&gt;</pre><div class="contentsignin">Copy after login</div></div> The child component will be the test component, so copy the below in the

test.vue

file Code block: <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class='brush:php;toolbar:false;'>&lt;template&gt; &lt;div&gt; &lt;slot&gt;&lt;/slot&gt; &lt;/div&gt; &lt;/template&gt; <script> export default { name: &#39;Test&#39; } </script></pre><div class="contentsignin">Copy after login</div></div> Use the following command to run the application in the development environment:

npm run serve
Copy after login

Named slotVue A component is allowed to have multiple slots, meaning you can have any number of slots. To test this functionality, copy this new code block into the

test.vue

file: <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class='brush:php;toolbar:false;'>&lt;template&gt; &lt;div&gt; &lt;slot&gt;&lt;/slot&gt; &lt;slot&gt;&lt;/slot&gt; &lt;slot&gt;&lt;/slot&gt; &lt;/div&gt; &lt;/template&gt; &lt;script&gt; export default { name: &amp;#39;Test&amp;#39; } &lt;/script&gt;</pre><div class="contentsignin">Copy after login</div></div> If you run the application, you can see

hello world

being printed Three times. So if you want to add more content (for example, a title, a paragraph with text, and then an unordered list), Vue allows us to name the scope so that it can identify the specific scope to display. Name the slots in the test.vue file as follows: <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class='brush:php;toolbar:false;'>&lt;template&gt; &lt;div&gt; &lt;slot name=&quot;header&quot;&gt;&lt;/slot&gt; &lt;slot name=&quot;paragraph&quot;&gt;&lt;/slot&gt; &lt;slot name=&quot;links&quot;&gt;&lt;/slot&gt; &lt;/div&gt; &lt;/template&gt; &lt;script&gt; export default { name: &amp;#39;Test&amp;#39; } &lt;/script&gt;</pre><div class="contentsignin">Copy after login</div></div> Now, you must also mark these HTML elements according to the slot name in which you want them to be displayed. Copy this to the template section of the

app.vue

file: <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class='brush:php;toolbar:false;'>&lt;template&gt; &lt;div id=&quot;app&quot;&gt; &lt;img alt=&quot;Vue logo&quot; src=&quot;./assets/logo.png&quot;&gt; &lt;Test&gt; &lt;h2 slot=&quot;header&quot;&gt;Hello world!&lt;/h2&gt; &lt;p slot=&quot;paragraph&quot;&gt;Hello, I am a paragraph text&lt;/p&gt; &lt;ul slot=&quot;links&quot;&gt; &lt;li&gt;Hello, I am a list item&lt;/li&gt; &lt;li&gt;Hello, I am a list item&lt;/li&gt; &lt;/ul&gt; &lt;/Test&gt; &lt;/div&gt; &lt;/template&gt;</pre><div class="contentsignin">Copy after login</div></div>

v-castle syntaxWhen the VUE version When 2.6 was released, it came with a better syntax for referencing slot names in subcomponents named

v-slot

, which meant replacing the initial slot syntax. So instead of replacing the parent component template with a slot like this: <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class='brush:php;toolbar:false;'>&lt;Test&gt; &lt;h1 slot=&quot;header&quot;&gt;Hello world!&lt;/h1&gt; &lt;/Test&gt;</pre><div class="contentsignin">Copy after login</div></div> Starting with version 3.0, it will now look like this:

<Test v-slot:header>
   <h1>Hello world!</h1>
</Test>
Copy after login

注意,除了字符串从slotv-slot的细微变化外,还有一个重大变化:v-slot只能在模板上定义,而不能在任何html元素上定义。这是一个很大的变化,因为它质疑命名插槽的可用性,但截至本文撰写之时,插槽仍然是文档的很大一部分。

作用域插槽

设想一个场景,其中Vue插槽还可以从父组件访问子组件中的数据对象,这是一种具有道具功能的插槽。要说明这一点,请继续,通过将下面的代码块复制到test.vue文件中,在子组件中创建一个数据对象:

<template>
  <div>
    <slot v-bind:team="team"></slot>
    <slot name="paragraph"></slot>
    <slot name="links"></slot>
  </div>
</template>
<script>
export default {
  name: &#39;Test&#39;,
  data(){
    return{
      team:"FC Barcelona"
    }
  }
}
</script>
Copy after login

与普通props一样,v-bind指令用于将数据中的团队与父组件中的prop引用绑定。打开app.vue文件并将下面的代码块复制到模板部分:

<template>
  <div id="app">
    <img alt="Vue logo" src="./assets/logo.png">
    <Test v-slot="{team}">
      <h2>Hello world! my team is {{team}}</h2>
    </Test>
  </div>
</template>
Copy after login

如果运行应用程序,您将看到数据对象已成功传递到父组件。

结论

本文向您介绍了vue.js中的插槽,以及它们对内容注入的重要性。您看到了如何设置它,甚至看到了如何为一个组件设置多个插槽。你还看到了狭槽如何通过作用域来充当道具。

英文原文地址:https://blog.logrocket.com/how-to-pass-html-content-through-components-with-vue-slots/

相关推荐:

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

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

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

The above is the detailed content of Using slots to pass data from parent component to child component 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 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks 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.

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.

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.

Analyze the principle of Vue2 implementing composition API Analyze the principle of Vue2 implementing composition API Jan 13, 2023 am 08:30 AM

Since the release of Vue3, the word composition API has entered the field of vision of students who write Vue. I believe everyone has always heard how much better the composition API is than the previous options API. Now, due to the release of the @vue/composition-api plug-in, Vue2 Students can also get on the bus. Next, we will mainly use responsive ref and reactive to conduct an in-depth analysis of how this plug-in achieves this.

Detailed example of vue3 realizing the typewriter effect of chatgpt Detailed example of vue3 realizing the typewriter effect of chatgpt Apr 18, 2023 pm 03:40 PM

When I was working on the chatgpt mirror site, I found that some mirror sites did not have typewriter cursor effects, but only text output. Did they not want to do it? I want to do it anyway. So I studied it carefully and realized the effect of typewriter plus cursor. Now I will share my solution and renderings~

See all articles