1.无名插槽
<body> <div id="app"> 123 </div> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> <script type="text/javascript"> //注册组件 Vue.component("my-component",{ template:"<span>Hello World!</span>" }) new Vue({ el:"#app", template:"<my-component>123</my-component>" }) </script> </body>
结果显示的是:Hello World!(组件中写的123并不显示)
当使用插槽时
<body> <div id="app"> 123 </div> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> <script type="text/javascript"> //注册组件 Vue.component("my-component",{ template:"<span>Hello World!<slot></slot></span>" }) new Vue({ el:"#app", template:"<my-component>123</my-component>" }) </script> </body>
结果显示的是:Hello World!123(组建中写的123显示了)
有<slot></slot>插槽的时候才可以显示自己组件中写的内容。
2.具名插槽
<body> <div id="app"> <my-component> <h1 slot="girl">我是女孩</h1> <h1 slot="boy">我是男孩</h1> <span slot>123</span> </my-component> </div> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> <script type="text/javascript"> //注册组件 Vue.component("my-component",{ template:` <div> <slot name="girl"></slot> <slot name="boy"></slot> <slot></slot> </div>` }) new Vue({ el:"#app" }) </script> </body>
显示结果:
我是女孩
我是男孩
123
3.作用域插槽
<body> <div id="app"> <my-component> <template slot-scope="a"> {{a}} </template> </my-component> </div> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> <script type="text/javascript"> //注册组件 Vue.component("my-component", { template: ` <div> <slot hah="hi"></slot> </div>` }) new Vue({ el: "#app" }) </script> </body>
显示结果为:
{ "hah": "hi" }