Vue中使用插槽(slot)、聚类插槽详解
主要介绍了Vue中使用插槽(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> 就会发现结果是
这个不是我的本意,那么怎么办,这里就引入了聚类插槽 template:`<div> <slot name='header'>默认内容</slot> <p>content</p> <slot name='footer'>默认内容</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)www.52php.cn</title> <script src="https://cdn.jsdelivr.net/npm/vue@2.5.17/dist/vue.js"></script> </head> <body> <div id="root"> <!-- 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)编程之家 www.52php.cn</title> <script src="https://cdn.jsdelivr.net/npm/vue@2.5.17/dist/vue.js"></script> </head> <body> <div id="root"> <!-- 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 name='header'>默认内容</slot> <p>content</p> <slot name='footer'>默认内容</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 name='header'>默认内容</slot> <p>content</p> <slot name='footer'>默认内容</slot> </div>` }); var vm = new Vue({ el:'#root', }); </script> </body> </html> (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |