1.做用/概念:预先将使用的内容进行保留javascript
个人理解就是父页面在组件标签内插入任意内容,子组件内插糟slot控制摆放位置(匿名插槽,具名插槽)vue
案例:java
<body> <div id='app'> <Hello> <div> 这里是插入的内容 //这一部分的内容并不会被输出(缘由是被组件覆盖掉了) </div> </Hello> </div> <template id="hello"> <div> <h3>这里是Hello组件</h3> </div> </template> </body> ////////////////////////////////////////////////////////////////////////注册组件部分 <script> Vue.component('Hello', { template: '#hello' }) new Vue({ el: '#app' }) </script>
从上面的案例能够看出 直接在组件里面写元素是没有做用的,这时候就须要插槽slotapp
一旦在组件中加入
案例:component
<template id="hello"> <div> <slot></slot> <h3>这里是Hello组件</h3> </div> </template>
<body> <div id='app'> <Hello> <header slot='header'>这里是头部</header> //这部插入的内容会被输出 <footer>这里是底部</footer> //这一部份内容不会被输出由于没有找到对应的插槽 </Hello> </div> <template id="hello"> <div> <slot name = "header"></slot> <h3>这里是Hello组件</h3> <slot name='footer'></slot> </div> </template> </body> <script> Vue.component('Hello', { template: '#hello' }) new Vue({ el: '#app' }) </script>
做用域插槽: 子组件内数据能够被父页面拿到(解决了数据只能从父页面传递给子组件)ip
v-slot (目前该属性并不完善)作用域
注意: 因为前两种插槽的形式在 vue2.6以上会被废弃,因此要使用v-slot指令来代替it
v-slot的好处:class
因此必须掌握
案例:
<div id="app"> <Hello> <template v-slot:header> <h1>Here might be a page title</h1> </template> <p>A paragraph for the main content.</p> <p>And another one.</p> <template v-slot:footer> <p>Here's some contact info</p> </template> </Hello> </div> <template id ='hello'> <div class="container"> <header> <!-- 咱们但愿把页头放这里 --> <slot name = "header"></slot> </header> <main> <!-- 咱们但愿把主要内容放这里 --> </main> <footer> <!-- 咱们但愿把页脚放这里 --> <slot name = 'footer'></slot> </footer> </div> </template> </body>