插槽的使用

父组件向子组件传递DOM

不具名插槽,如下:

  父组件的内容如下:

1 <template>
2   <div id="app">
3     <home>
4       <p>hello lanyb</p> //父组件往子组件中插入的内容
5     </home>
6   </div>
7 </template>

  子组件中的内容如下:

1 <template>
2   <div>
3     hello world
4     <slot></slot> //父组件要插入的内容将插入在此处
5   </div>
6 </template>

输出结果为:

hello world
hello lanyb

以上就是最简单的slot示例。

然后还有具名插槽,如下:

  父组件中的内容,如下:

1 <template>
2   <div id="app">
3     <home>
4       <p slot="header">hello lanyb</p> //定义两个具名插槽
5       <p slot="ender">hello world</p> //定义两个具名插槽
6     </home>
7   </div>
8 </template>

  子组件中的内容,如下:

1 <template>
2   <div>
3     <slot name="ender"></slot> //名字叫ender的插槽中的内容会插入至此
4     我是分割线
5     <slot name="header"></slot> //名字叫header的插槽中的内容会插入到此
6   </div>
7 </template>

显示结果为:

hello world
我是分割线
hello lanyb

注意:不具名插槽只有1个,具名插槽具有多个

猜你喜欢

转载自www.cnblogs.com/lanyb009/p/9235985.html