详解Vue中使用插槽(slot)、聚类插槽

一、基本的插槽

这里总结两点

如果不在子组件中使用插槽(slot),那么在子组件中写任何代码都是无效的的,不会显示

(插槽默认值)如果子组件中没有插入任何代码的话就会显示组件插槽中的内容

slot 代表父组件往子组件中 插入的标签
这里就代表组件子组件中的 

<p>Dell</p> <child> <p>Dell</p> </child>

这里如果是这样的

<child> </child>

就会显示 <slot>默认内容</slot>中的默认内容 

二、聚类插槽

1、如果不在子组件中使用插槽(slot),那么在子组件中写任何代码都是无效的的,不会显示

2、(插槽默认值)如果子组件中没有插入任何代码的话就会显示组件插槽中的内容

这里如果是这样的

<child> </child>

就会显示<slot>默认内容</slot>中的 默认内容

3、聚类插槽

子组件这么写:

template:`<div> <slot>默认内容</slot> <p>content</p> <slot>默认内容</slot> </div>

然后这么引用:

<child> <div>header</div> <div>footer</div> </child>

就会发现结果是

header
footer
content
header
 footer

这个不是我的本意,那么怎么办,这里就引入了聚类插槽
子组件:

template:`<div> <slot>默认内容</slot> <p>content</p> <slot>默认内容</slot> </div>`

子组件引用:

<child> <div slot='header'>header</div> <div slot='footer'>footer</div> </child>

不难发现给每个想要指定的子组件插槽添加 name属性,然后在引用中 slot中明确 是哪个即可也可以理解为引用中是用了两个插槽同时,默认内容同时适用在每个插槽

三、作用域插槽

这个是普通插槽的Demo

<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Vue中使用插槽(slot)</title> <script src="https://cdn.jsdelivr.net/npm/vue@2.5.17/dist/vue.js"></script> </head> <body> <div> <!-- 1、如果不在子组件中使用插槽(slot),那么在子组件中写任何代码都是无效的的,不会显示 2、(插槽默认值)如果子组件中没有插入任何代码的话就会显示组件插槽中的内容 这里如果是这样的 <child> </child> 就会显示 <slot>默认内容</slot>中的 默认内容 --> <child> <p>Dell</p> </child> </div> <script type="text/javascript"> Vue.component('child',{ /* slot 代表 父组件往子组件中 插入的标签 这里就代表 组件子组件中的 <p>Dell</p> <child> <p>Dell</p> </child> */ template:`<div> <slot>默认内容</slot> </div>` }); var vm = new Vue({ el:'#root', }); </script> </body> </html>

这个是聚类插槽的Demo

<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Vue中使用插槽(slot)</title> <script src="https://cdn.jsdelivr.net/npm/vue@2.5.17/dist/vue.js"></script> </head> <body> <div> <!-- 1、如果不在子组件中使用插槽(slot),那么在子组件中写任何代码都是无效的的,不会显示 2、(插槽默认值)如果子组件中没有插入任何代码的话就会显示组件插槽中的内容 这里如果是这样的 <child> </child> 就会显示 <slot>默认内容</slot>中的 默认内容 3、聚类插槽 子组件这么写: template:`<div> <slot>默认内容</slot> <p>content</p> <slot>默认内容</slot> </div>` 然后这么引用: <child> <div>header</div> <div>footer</div> </child> 就会发现结果是 header footer content header footer 这个不是我的本意,那么怎么办,这里就引入了聚类插槽 子组件: template:`<div> <slot>默认内容</slot> <p>content</p> <slot>默认内容</slot> </div>` 子组件引用: <child> <div slot='header'>header</div> <div slot='footer'>footer</div> </child> 不难发现给每个想要指定的子组件插槽添加 name属性, 然后在引用中 slot中明确 是哪个即可 也可以理解为引用中是用了两个插槽 同时,默认内容同时适用在每个插槽 --> <child> <div slot='header'>default header</div> <div slot='footer'>default footer</div> </child> </div> <script type="text/javascript"> Vue.component('child',{ /* slot 代表 父组件往子组件中 插入的标签 这里就代表 组件子组件中的 <p>Dell</p> <child> <p>Dell</p> </child> */ template:`<div> <slot>默认内容</slot> <p>content</p> <slot>默认内容</slot> </div>` }); var vm = new Vue({ el:'#root', }); </script> </body> </html>

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/c25516f2a67013c2e39ea88617dfaafd.html