vue3 插槽
基本使用
<div > <my-component>abc</my-component> </div> <script type="module"> import * as obj from './main.js' const app = Vue.createApp({ }); app.component('my-component', obj.btn1) const vm = app.mount('#vm'); </script>
js
const btn1 = { template: ` <div class="demo-alert-box"> <strong>Error!</strong> <slot></slot> </div>`, } export { btn1 }
相当于把组件之间的数据abc放到的slot插槽上。
除了可以在组件间放普通文字外,还可以使html代码或者其他模板
作用域???
默认值
<div > <my-component>ccc</my-component> </div> <script type="module"> import * as obj from './main.js' const app = Vue.createApp({ }); app.component('my-component', obj.btn1) const vm = app.mount('#vm'); </script>
子组件的插槽中填入数据,作为默认值
const btn1 = { template: ` <div class="demo-alert-box"> <strong>Error!</strong> <slot>abc</slot> </div>`, } export { btn1 }
具名插槽
父组件使用<template v-slot:名字>的方式对应指定子组件的插槽
<div > <my-component> <template v-slot:header> <h1>Here might be a page title</h1> </template> <template v-slot:default> <p>A paragraph for the main content.</p> <p>And another one.</p> </template> <template v-slot:footer> <p>Here's some contact info</p> </template> </my-component> </div> <script type="module"> import * as obj from './main.js' const app = Vue.createApp({ }); app.component('my-component', obj.btn1) const vm = app.mount('#vm'); </script>
slot元素的name属性用来定义额外的插槽
const btn1 = { template: ` <div class="container"> <header> <slot name="header"></slot> </header> <main> <slot></slot> </main> <footer> <slot name="footer"></slot> </footer> </div> `, } export { btn1 }
v-slot:default 表示使用默认插槽<slot></slot>
父组件中可以使用缩写<template #header> 代替 <template v-slot:header>