21 插槽
插槽
# 在定义组件是,预留一个地方使用标签 <slot></slot> 占位
# 以后在父组件中的子组件的标签内部写 内容,html内容 就会被替换到<slot></slot>中
1 slot插槽 (内容分发)
a. 单个slot
b. 具名slot
*混合父组件的内容与子组件自己的模板-->内容分发
*父组件模板的内容在父组件作用域内编译;子组件模板的内容在子组件作用域内编译。
1.1 插槽基本使用
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="js/vue.js"></script> </head> <body> <div id="box"> <!-- 不使用插槽写的aaa不会显示,使用就会显示--> <child1>aaa</child1> </div> </body> <script> var bus = new Vue() //new一个vue的实例,就是中央事件总线 Vue.component('child1', { template: `<div> 首页 <slot></slot> </div>`, }) var vm = new Vue({ el: '#box', }) </script> </html>
1.2 具名插槽
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="js/vue.js"></script> </head> <body> <div id="box"> <!-- 具名插槽,把p标签给a插槽,div标签给b插槽--> <navbar> <p slot="a">pppp</p> <div slot="b">bbbb</div> </navbar> </div> </body> <script> Vue.component('navbar', { template: `<div> <slot name="a"></slot> navbar <slot name="b"></slot> </div>`, }) var vm = new Vue({ el: '#box', data:{ } }) </script> </html>