vue 实现了一套内容分发的 API, 这套 API 的设计灵感源自 web Components 规范草案, 将 < slot > 元素作为承载分发内容的出口. 本文为大家详细介绍了 vue 中的插槽, 希望对大家有一定的帮助.
一, 插槽内容
一句话: 插槽内可以是任意内容.
先看一下下面的代码: 声明一个 child-component 组件,
如果现在我想在 < child-component></child-component > 内放置一些内容, 结果会是怎样?
- <div id="app">
- <child-component></child-component>
- </div>
- <script>
- Vue.component('child-component',{
- template:`
- <div>Hello,World!</div>
- `
- })
- let vm = new Vue({
- el:'#app',
- data:{
- }
- })
- </script>
- <child-component > 你好 </child-component>
输出内容还是在组件中的内容, 在 <child-component > 内写的内容没起作用.
我们现在给组件增加一个 < slot></slot > 插槽
我们在 < child-component></child-component > 内写的 "你好" 起作用了!!!
- Vue.component('child-component',{
- template:`
- <div>
- Hello,World!
- <slot></slot>
- </div>
- `
- })
到现在, 我们知道了什么是插槽:
插槽就是 Vue 实现的一套内容分发的 API, 将 < slot></slot > 元素作为承载分发内容的出口.
这句话的意思就是, 没有插槽的情况下在组件标签内些一些内容是不起任何作用的, 当我在组件中声明了 slot 元素后, 在组件元素内写的内容就会跑到它这里了!
二, 具名插槽
具名插槽, 就是给这个插槽起个名字
在组件中, 我给插槽起个名字, 一个名字叫 "girl", 一个名字叫 "boy", 还有一个不起名字.
然后再 < child-component></child-component > 内, slot 属性对应的内容都会和组件中 name 一一对应.
而没有名字的, 就是默认插槽!!
- <div id="app">
- <child-component>
- <template slot="girl">
漂亮, 美丽, 购物, 逛街
- </template>
- <template slot="boy">
帅气, 才实
- </template>
- <div>
我是一类人,
我是默认的插槽
- </div>
- </child-component>
- </div>
- <script>
- Vue.component('child-component',{
- template:`
- <div>
- <h4 > 这个世界不仅有男人和女人 </h4>
- <slot name="girl"></slot>
- <div style="height:1px;background-color:red;"></div>
- <slot name="boy"></slot>
- <div style="height:1px;background-color:red;"></div>
- <slot></slot>
- </div>
- `
- })
- let vm = new Vue({
- el:'#app',
- data:{
- }
- })
- </script>
3, 作用域插槽
之前一直没搞懂作用域插槽到底是什么!!!
说白了就是我在组件上的属性, 可以在组件元素内使用!
先看一个最简单的例子!!
我们给 < slot></slot > 元素上定义一个属性 say(随便定义的!), 接下来在使用组件 child, 然后在 template 元素上添加属性 slot-scope!! 随便起个名字 a
我们把 a 打印一下发现是 {"say" : "你好"}, 也就是 slot 上面的属性和值组成的键值对!!!
这就是作用域插槽!
我可以把组件上的属性 / 值, 在组件元素上使用!!
- <div id="app">
- <child>
- <template slot-scope="a">
- <!-- {"say":"你好"} -->
- {{a}}
- </template>
- </child>
- </div>
- <script>
- Vue.component('child',{
- template:`
- <div>
- <slot say="你好"></slot>
- </div>
- `
- })
- let vm = new Vue({
- el:'#app',
- data:{
- }
- })
- </script>
再看一下下面的例子:
- <div id="app">
- <child :lists="nameList">
- <template slot-scope="a">
- {{a}}
- </template>
- </child>
- </div>
- <script>
- Vue.component('child',{
- props:['lists'],
- template:`
- <div>
- <ul>
- <li v-for="list in lists">
- <slot :bbbbb="list"></slot>
- </li>
- </ul>
- </div>
- `
- })
- let vm = new Vue({
- el:'#app',
- data:{
- nameList:[
- {id:1,name:'孙悟空'},
- {id:2,name:'猪八戒'},
- {id:3,name:'沙和尚'},
- {id:4,name:'唐僧'},
- {id:5,name:'小白龙'},
- ]
- }
- })
- </script>
看一下输出结果
本文来自 html 中文网 vue.js 教程 https://www.html.cn/web/vue-js/ 栏目.
来源: http://www.css88.com/web/vue-js/15418.html