vue slot插槽
Posted giser123
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了vue slot插槽相关的知识,希望对你有一定的参考价值。
插槽(Slot)是Vue提出来的一个概念,正如名字一样,插槽用于决定将所携带的内容,插入到指定的某个位置,从而使模板分块具有模块化的特质和更大的重用性。
单个插槽
- <template>
- <div id="example">
- <h1>我是父组件的标题</h1>
- <app-layout>
- <p>主要内容的一个段落。</p>
- <p>另一个主要段落。</p>
- <p slot="footer">这里有一些联系信息</p>
- <h1 slot="header">这里可能是一个页面标题</h1>
- </app-layout>
- </div>
- </template>
- <script>
- export default{
- components:{
- ‘app-layout‘: {
- template: `
- <div>
- <h2>我是子组件的标题</h2>
- <slot>
- 只有在没有要分发的内容时才会显示。
- </slot>
- </div>
- `,
- }
- }
- }
- </script>
执行结果
- <div>
- <h1>我是父组件的标题</h1>
- <div>
- <h2>我是子组件的标题</h2>
- <p>这是一些初始内容</p>
- <p>这是更多的初始内容</p>
- </div>
- </div>
具名插槽
- <template>
- <div id="example">
- <h1>我是父组件的标题</h1>
- <app-layout>
- <h1 slot="header">这里可能是一个页面标题</h1>
- <p>主要内容的一个段落。</p>
- <p>另一个主要段落。</p>
- <p slot="footer">这里有一些联系信息</p>
- </app-layout>
- </div>
- </template>
- <script>
- export default{
- components:{
- ‘app-layout‘: {
- template: `
- <div class="container">
- <header>
- <slot name="header"></slot>
- </header>
- <main>
- <slot></slot>
- </main>
- <footer>
- <slot name="footer"></slot>
- </footer>
- </div>
- `,
- }
- }
- }
- </script>
执行结果
- <div class="container">
- <header>
- <h1>这里可能是一个页面标题</h1>
- </header>
- <main>
- <p>主要内容的一个段落。</p>
- <p>另一个主要段落。</p>
- </main>
- <footer>
- <p>这里有一些联系信息</p>
- </footer>
- </div>
作用域插槽
- <template>
- <div id="example">
- <div class="parent">
- <child>
- <template slot-scope="props">
- <span>hello from parent</span><br/>
- <span>{{ props.text }}</span>
- </template>
- </child>
- </div>
- </div>
- </template>
- <script>
- export default{
- components:{
- ‘child‘: {
- template: `
- <div class="child">
- <slot text="hello from child"></slot>
- </div>
- `,
- }
- }
- }
- </script>
执行结果为
- <div class="parent">
- <div class="child">
- <span>hello from parent</span>
- <span>hello from child</span>
- </div>
- </div>
以上是关于vue slot插槽的主要内容,如果未能解决你的问题,请参考以下文章