


Using slots to pass data from parent component to child component in Vue.js
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.
#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-cliThen, install the new one:
npm install -g @ vue / cli
- Download here
- Unzip the downloaded project
- Navigate to the unzipped file and run the command to keep all dependencies up to date :
npm install
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?
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>The parent component (where the HTML content to be injected into the child component resides) could look like this:
<Test> <h2 id="Hello-nbsp-World">Hello World!</h2> </Test>This combination will return a user interface that looks like this:
<template> <div> <h2 id="Hello-nbsp-World">Hello World!</h2> </div> </template>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 openvue 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: <pre class='brush:php;toolbar:false;'><template>
<div id="app">
<img src="/static/imghwm/default1.png" data-src="./assets/logo.png" class="lazy" alt="Vue logo" >
<Test>
<h2 id="Hello-nbsp-World">Hello World!</h2>
</Test>
</div>
</template>
<script>
import Test from &#39;./components/Test.vue&#39;
export default {
name: &#39;app&#39;,
components: {
Test
}
}
</script></pre>
The child component will be the test component, so copy the below in the
file Code block: <pre class='brush:php;toolbar:false;'><template>
<div>
<slot></slot>
</div>
</template>
<script>
export default {
name: 'Test'
}
</script></pre>
Use the following command to run the application in the development environment:
npm run serve
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: <pre class='brush:php;toolbar:false;'><template>
<div>
<slot></slot>
<slot></slot>
<slot></slot>
</div>
</template>
<script>
export default {
name: &#39;Test&#39;
}
</script></pre>
If you run the application, you can see
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: <pre class='brush:php;toolbar:false;'><template>
<div>
<slot name="header"></slot>
<slot name="paragraph"></slot>
<slot name="links"></slot>
</div>
</template>
<script>
export default {
name: &#39;Test&#39;
}
</script></pre>
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
file: <pre class='brush:php;toolbar:false;'><template>
<div id="app">
<img src="/static/imghwm/default1.png" data-src="./assets/logo.png" class="lazy" alt="Vue logo" >
<Test>
<h2 id="Hello-nbsp-world">Hello world!</h2>
<p slot="paragraph">Hello, I am a paragraph text</p>
<ul slot="links">
<li>Hello, I am a list item</li>
<li>Hello, I am a list item</li>
</ul>
</Test>
</div>
</template></pre>
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: <pre class='brush:php;toolbar:false;'><Test>
<h1 id="Hello-nbsp-world">Hello world!</h1>
</Test></pre>
Starting with version 3.0, it will now look like this:
<Test v-slot:header> <h1 id="Hello-nbsp-world">Hello world!</h1> </Test>
注意,除了字符串从slot
到v-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: 'Test', data(){ return{ team:"FC Barcelona" } } } </script>
与普通props
一样,v-bind
指令用于将数据中的团队与父组件中的prop
引用绑定。打开app.vue
文件并将下面的代码块复制到模板部分:
<template> <div id="app"> <img src="/static/imghwm/default1.png" data-src="./assets/logo.png" class="lazy" alt="Vue logo" > <Test v-slot="{team}"> <h2 id="Hello-nbsp-world-nbsp-my-nbsp-team-nbsp-is-nbsp-team">Hello world! my team is {{team}}</h2> </Test> </div> </template>
如果运行应用程序,您将看到数据对象已成功传递到父组件。
结论
本文向您介绍了vue.js中的插槽,以及它们对内容注入的重要性。您看到了如何设置它,甚至看到了如何为一个组件设置多个插槽。你还看到了狭槽如何通过作用域来充当道具。
英文原文地址:https://blog.logrocket.com/how-to-pass-html-content-through-components-with-vue-slots/
相关推荐:
更多编程相关知识,请访问:编程入门!!
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!

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Atom editor mac version download
The most popular open source editor

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

Dreamweaver CS6
Visual web development tools