search
HomeWeb Front-endFront-end Q&AWhat problem does vue slot solve?

What problem does vue slot solve?

Jan 13, 2023 pm 06:26 PM
vueslot

The problem solved by the vue slot: Content is not allowed to be written in the middle of the introduced sub-component tags. Slot is a capability provided by Vue for component packagers; it allows developers to define uncertain parts that are expected to be specified by the user as slots when packaging components; slots can be considered as during component packaging. A placeholder for content reserved for the user.

What problem does vue slot solve?

The operating environment of this tutorial: windows7 system, vue3 version, DELL G3 computer.

What is a slot?

We know that in vue, content is not allowed to be written in the middle of the introduced sub-component tags. In order to solve this problem, the official introduced the concept of slot.

Slots are actually equivalent to placeholders. It gives your HTML template a place in the component, allowing you to pass in some stuff. Slots are divided into anonymous slots, named slots and scoped slots.

You may not quite understand why I need to pass HTML into the subcomponent instead of writing it directly in the subcomponent? The answer is this. You can imagine a scenario where you have five pages. Only one area of ​​the five pages has different content. How would you write these five pages? Copy and paste is one way, but in vue, slots are better.

What problem does vue slot solve?

##Anonymous slot


Anonymous slot, we can call it a single slot slot or default slot. In contrast to named slots, it does not require the name attribute to be set. (Its hidden name attribute is default.)

Example:

The file directory is as follows, and the Home component is the parent component of HelloWorld.

What problem does vue slot solve?

    Write an anonymous slot in HelloWorld
<template>
  <div>
     Helloworld组件

     <div>
       <slot></slot>
     </div>

  </div>
</template>

<script>
export default {

}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style>
.hello{
  width:100%;
  height:300px;
  background:#ccc;
  margin-top:50px;
  .slotTxt{
    width:500px;
    height:200px;
    margin:30px auto;
    background:red;
  }
}
</style>
    Introduce sub-component in Home component and add it in sub-component Content written in the component tag
<template>
  <div>
    我是Home父组件
    <helloworld>
      <!-- 没有插槽,这里的内容不显示 -->
      <h1 id="我是helloworld中的插槽啊">我是helloworld中的插槽啊</h1>  
    </helloworld>
  </div>
</template>

<script>
import HelloWorld from &#39;@/components/HelloWorld.vue&#39;
export default {
  name: &#39;home&#39;,
  components: {
    HelloWorld
  }
}
</script>
Effect

What problem does vue slot solve?

It is not difficult to see that the content (red part) in the HelloWorld tag has been displayed.

Named Slot


As mentioned above, the slot has a name attribute. As opposed to anonymous slots, anonymous slots with the name attribute added are named slots.

    Write the slots whose name attributes are left and right respectively in the HelloWorld component
<template>
  <div>
     Helloworld组件

     <div>
       <slot></slot>
     </div>

     <div>
       <slot></slot>
     </div>

  </div>
</template>

<script>
export default {

}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style>
.hello{
  width:700px;
  height:300px;
  background:#ccc;
  margin: 0 auto;
  margin-top:50px;
  .slotLeft{
    width:300px;
    height:200px;
    float:left;
    background:red;
  }
  .slotRight{
    width:300px;
    height:200px;
    float:right;
    background:pink;
  }
}
</style>
    Home component writes v-slot:name on the template Use named slots
<template>
  <div>
    我是Home父组件
    <helloworld>
      <template>
         <h1 id="name属性为left">name属性为left</h1> 
      </template>
      <template>
         <h1 id="name属性为right">name属性为right</h1> 
      </template>
     
    </helloworld>
  </div>
</template>

<script>
import HelloWorld from &#39;@/components/HelloWorld.vue&#39;
export default {
  name: &#39;home&#39;,
  components: {
    HelloWorld
  }
}
</script>
<style>
.home{
  width:900px;
  margin:0 auto;
  background:yellow;
  padding-bottom:100px;
}
</style>

Note that v-slot can only be added on the template tag (with one exception).

  • Effect

What problem does vue slot solve?

##Exception (Abandoned slot='name ')
    Named slots with slot attributes have been abandoned since 2.6.0, and vue3.x has been completely abandoned. Only cli before vue3 can be used.

  • <template>
      <div>
        我是Home父组件
        <helloworld>
          <h1 id="name属性为left">name属性为left</h1>  
          <h1 id="name属性为right">name属性为right</h1>  
        </helloworld>
      </div>
    </template>
    
    <script>
    import HelloWorld from &#39;@/components/HelloWorld.vue&#39;
    export default {
      name: &#39;home&#39;,
      components: {
        HelloWorld
      }
    }
    </script>
    <style>
    .home{
      width:900px;
      margin:0 auto;
      background:yellow;
      padding-bottom:100px;
    }
    </style>
  • The effect is the same as above.

Little knowledge about named slots
    Like v-on and v-bind, v-slot also has an abbreviation, that is, replace everything before the parameter (v-slot:) with character#. For example v-slot:header can be rewritten as #header.

Scope slot

A scope slot is actually a slot that can pass data. If some data in the child component is to be used in the parent component, it must be passed through specified methods. A rule is proposed in the official documentation that **all content in the parent template is compiled in the parent scope. Everything inside a child template is compiled in the child scope. **If you use the value in the child component directly in the parent component, an error will be reported.

Scope slot of anonymous slot

In order to make the data in the child component available in the parent's slot content, we can use the data as the element's A property is bound:

语法:v-bind:users="user"

Subcomponent HelloWorld code
  • <template>
      <div>
         Helloworld组件  
         <div>
           <slot></slot>
         </div> 
         
      </div>
    </template>
    
    <script>
    export default {
      data(){
        return{
          user:{
            name:&#39;oralinge&#39;,
            age:18
          }
        }  
      }
    }
    </script>
    
    <!-- Add "scoped" attribute to limit CSS to this component only -->
    <style>
    .hello{
      width:700px;
      height:300px;
      background:#ccc;
      margin: 0 auto;
      margin-top:50px;
      .slotLeft{
        width:300px;
        height:200px;
        // float:left;
        background:red;
        margin:20px auto
      }
      .slotRight{
        width:300px;
        height:200px;
        float:right;
        background:pink;
      }
    }
    </style>
  • The property bound to the element (v-bind:users="user") is called for the slot prop. Now in the parent scope, we can use v-slot with a value to define the name of the slot prop we provide.
语法:v-slot:default="随意取的名字"  // default可省略,简写为v-slot="随意取的名字"

Parent component Home code
  • <template>
      <div>
        我是Home父组件
        <helloworld>
          <template>
             <h1 id="slotProps-users-name">{{slotProps.users.name}}</h1> 
          </template>
        </helloworld>
      </div>
    </template>
    
    <script>
    import HelloWorld from &#39;@/components/HelloWorld.vue&#39;
    export default {
      name: &#39;home&#39;,
      components: {
        HelloWorld
      }
    }
    </script>
    <style>
    .home{
      width:900px;
      margin:0 auto;
      background:yellow;
      padding-bottom:100px;
    }
    </style>
  • Note:
The slotProps in the parent component can be taken at will.

The users in the sub-component are chosen at will, corresponding to the users in the parent component.
The user in the subcomponent is data.

Effect

What problem does vue slot solve?

The scope slot of the named slot

The same as the anonymous slot, only You need to replace default with the name value of the slot.

Sub component HelloWorld code
  • <template>
      <div>
         Helloworld组件  
         <div>
           <slot></slot>
         </div> 
         
      </div>
    </template>
    
    <script>
    export default {
      data(){
        return{
          user:{
            name:&#39;hello world&#39;,
            age:18
          }
        }  
      }
    }
    </script>
    
    <!-- Add "scoped" attribute to limit CSS to this component only -->
    <style>
    .hello{
      width:700px;
      height:300px;
      background:#ccc;
      margin: 0 auto;
      margin-top:50px;
      .slotLeft{
        width:300px;
        height:200px;
        // float:left;
        background:red;
        margin:20px auto
      }
      .slotRight{
        width:300px;
        height:200px;
        float:right;
        background:pink;
      }
    }
    </style>
Parent component Home code
  • <template>
      <div>
        我是Home父组件
        <helloworld>
          <template>
             <h1 id="slotProps-users-name">{{slotProps.users.name}}</h1> 
          </template>
        </helloworld>
      </div>
    </template>
    
    <script>
    import HelloWorld from &#39;@/components/HelloWorld.vue&#39;
    export default {
      name: &#39;home&#39;,
      components: {
        HelloWorld
      }
    }
    </script>
    <style>
    .home{
      width:900px;
      margin:0 auto;
      background:yellow;
      padding-bottom:100px;
    }
    </style>
  • Effect

What problem does vue slot solve?

注意:
     默认插槽的缩写语法不能和具名插槽混用,因为它会导致作用域不明确。

What problem does vue slot solve?

另,slot-scope写法在2.6之后已废弃,作用与上面相同,在此不做解释。

上面的写法是不是觉得有些麻烦?别着急,我们来看一看解构插槽 Prop

解构插槽 Prop

作用域插槽的内部工作原理是将你的插槽内容包括在一个传入单个参数的函数里:

function (slotProps) {
  // 插槽内容
}

这意味着 v-slot 的值实际上可以是任何能够作为函数定义中的参数的 JavaScript 表达式。所以在支持的环境下 (单文件组件或现代浏览器),你也可以使用 ES2015 解构来传入具体的插槽 prop。

语法:v-slot="{ users }"
  • HelloWold组件
<template>
  <div>
     Helloworld组件  
     <div>
       <slot></slot>
     </div> 
     
  </div>
</template>

<script>
export default {
  data(){
    return{
      user:{
        name:&#39;hello world&#39;,
        age:18
      }
    }  
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style>
.hello{
  width:700px;
  height:300px;
  background:#ccc;
  margin: 0 auto;
  margin-top:50px;
  .slotLeft{
    width:300px;
    height:200px;
    // float:left;
    background:red;
    margin:20px auto
  }
  .slotRight{
    width:300px;
    height:200px;
    float:right;
    background:pink;
  }
}
</style>
  • Home组件
<template>
  <div>
    我是Home父组件
    <helloworld>
      <template>
         <h1 id="users-name">{{users.name}}</h1> 
      </template>
    </helloworld>
  </div>
</template>

<script>
import HelloWorld from &#39;@/components/HelloWorld.vue&#39;
export default {
  name: &#39;home&#39;,
  components: {
    HelloWorld
  }
}
</script>
<style>
.home{
  width:900px;
  margin:0 auto;
  background:yellow;
  padding-bottom:100px;
}
</style>
  • 效果

What problem does vue slot solve?

  • 重命名----更改users这个名字
<template>
  <div>
    我是Home父组件
    <helloworld>
      <template>
         <h1 id="person-name">{{person.name}}</h1> 
      </template>
    </helloworld>
  </div>
</template>

<script>
import HelloWorld from &#39;@/components/HelloWorld.vue&#39;
export default {
  name: &#39;home&#39;,
  components: {
    HelloWorld
  }
}
</script>
<style>
.home{
  width:900px;
  margin:0 auto;
  background:yellow;
  padding-bottom:100px;
}
</style>

效果如上图。

  • 定义后备内容,用于插槽 prop 是 undefined 的情形
    此处按照官方文档的写法会出现语法报错,后期应该会修复(有知道的麻烦通知一声)。
<template>
  <div>
    我是Home父组件
    <helloworld>
      <template>
         <h1 id="users-name">{{users.name}}</h1> 
      </template>
    </helloworld>
  </div>
</template>

<script>
import HelloWorld from &#39;@/components/HelloWorld.vue&#39;
export default {
  name: &#39;home&#39;,
  components: {
    HelloWorld
  }
}
</script>
<style>
.home{
  width:900px;
  margin:0 auto;
  background:yellow;
  padding-bottom:100px;
}
</style>

使用场景


  • 复用公共组件
    代码示例如下:
<template>
  <div>
    <div>
      <span>{{title}}</span>
      <div>
        <slot></slot>
      </div>
    </div>
    <div>
      <slot></slot>
    </div>
  </div>
</template>
<script>
export default {
  data () {
    return {
    }
  },
  props: {
    title: {
      type: String,
      required: true
    }
  }
}
</script>
<style>
.title-box {
  padding: 16px 0;
  border-bottom: 1px solid #eff1f5;
  .title {
    font-family: MicrosoftYaHei;
    font-size: 24px;
    color: #283039;
    letter-spacing: 0;
    line-height: 24px;
    &::before {
      width: 4px;
      margin-right: 20px;
      content: "";
      background-color: #5da1ff;
      display: inline-block;
      height: 20px;
      vertical-align: middle;
    }
  }
  .right {
    float: right;
    margin-right: 20px;
  }
}
</style>

使用的ui框架为ivew。

相关推荐:vue.js视频教程

The above is the detailed content of What problem does vue slot solve?. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
How to Use useState() Hook in Functional React ComponentsHow to Use useState() Hook in Functional React ComponentsApr 30, 2025 am 12:25 AM

useState allows state to be added in function components because it removes obstacles between class components and function components, making the latter equally powerful. The steps to using useState include: 1) importing the useState hook, 2) initializing the state, 3) using the state and updating the function.

React's View-Focused Nature: Managing Complex Application StateReact's View-Focused Nature: Managing Complex Application StateApr 30, 2025 am 12:25 AM

React's view focus manages complex application state by introducing additional tools and patterns. 1) React itself does not handle state management, and focuses on mapping states to views. 2) Complex applications need to use Redux, MobX, or ContextAPI to decouple states, making management more structured and predictable.

Integrating React with Other Libraries and FrameworksIntegrating React with Other Libraries and FrameworksApr 30, 2025 am 12:24 AM

IntegratingReactwithotherlibrariesandframeworkscanenhanceapplicationcapabilitiesbyleveragingdifferenttools'strengths.BenefitsincludestreamlinedstatemanagementwithReduxandrobustbackendintegrationwithDjango,butchallengesinvolveincreasedcomplexity,perfo

Accessibility Considerations with React: Building Inclusive UIsAccessibility Considerations with React: Building Inclusive UIsApr 30, 2025 am 12:21 AM

TomakeReactapplicationsmoreaccessible,followthesesteps:1)UsesemanticHTMLelementsinJSXforbetternavigationandSEO.2)Implementfocusmanagementforkeyboardusers,especiallyinmodals.3)UtilizeReacthookslikeuseEffecttomanagedynamiccontentchangesandARIAliveregio

SEO Challenges with React: Addressing Client-Side Rendering IssuesSEO Challenges with React: Addressing Client-Side Rendering IssuesApr 30, 2025 am 12:19 AM

SEO for React applications can be solved by the following methods: 1. Implement server-side rendering (SSR), such as using Next.js; 2. Use dynamic rendering, such as pre-rendering pages through Prerender.io or Puppeteer; 3. Optimize application performance and use Lighthouse for performance auditing.

The Benefits of React's Strong Community and EcosystemThe Benefits of React's Strong Community and EcosystemApr 29, 2025 am 12:46 AM

React'sstrongcommunityandecosystemoffernumerousbenefits:1)ImmediateaccesstosolutionsthroughplatformslikeStackOverflowandGitHub;2)Awealthoflibrariesandtools,suchasUIcomponentlibrarieslikeChakraUI,thatenhancedevelopmentefficiency;3)Diversestatemanageme

React Native for Mobile Development: Building Cross-Platform AppsReact Native for Mobile Development: Building Cross-Platform AppsApr 29, 2025 am 12:43 AM

ReactNativeischosenformobiledevelopmentbecauseitallowsdeveloperstowritecodeonceanddeployitonmultipleplatforms,reducingdevelopmenttimeandcosts.Itoffersnear-nativeperformance,athrivingcommunity,andleveragesexistingwebdevelopmentskills.KeytomasteringRea

Updating State Correctly with useState() in ReactUpdating State Correctly with useState() in ReactApr 29, 2025 am 12:42 AM

Correct update of useState() state in React requires understanding the details of state management. 1) Use functional updates to handle asynchronous updates. 2) Create a new state object or array to avoid directly modifying the state. 3) Use a single state object to manage complex forms. 4) Use anti-shake technology to optimize performance. These methods can help developers avoid common problems and write more robust React applications.

See all articles

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools