slot 作为 vue 进行内容分发的重要组成, 对其作用一直是模模糊糊的, 今天研究了一下, 特意记录一些体会, 希望对阅读到的你有所帮助.
slot 分为默认插槽, 具名插槽和作用域插槽, 默认插槽和具名插槽相对简单, 上代码:
- <!-- 在子组件中预留 slot 标签 -->
- <template>
- <div class="hello">
- <!-- 默认插槽 -->
- <h1 > 这里是头部 </h1>
- <slot></slot>
- <!-- 具名插槽 -->
- <h1>{{ msg }}</h1>
- <slot name="content"></slot>
- <h1 > 这里是底部 </h1>
- <slot name="footer"></slot>
- </div>
- </template>
- <!-- 在父组件中填写子组件中的 slot -->
- <template>
- <div class="home">
- <HelloWorld msg="这里是 Content">
- <!-- 默认插槽 -->
- <template>
- <span class="text" v-for="item in nav" :key="item.id">
- {{ item.label }}
- </span>
- </template>
- <!-- 具名插槽 -->
- <template v-slot:content>
- <div class="text" @click="contentFn">
这里是内容的具体内容
- </div>
- </template>
- <template v-slot:footer>
- <div class="text">
这里是底部的具体内容
- </div>
- </template>
- </HelloWorld>
- </div>
- </template>
- <script>
- // @ is an alias to /src
- import HelloWorld from "@/components/HelloWorld.vue";
- export default {
- name: "Home",
- components: {
- HelloWorld
- },
- data() {
- return {
- nav: [
- { label: "水果", id: 1 },
- { label: "旅游", id: 2 },
- { label: "国家", id: 3 },
- { label: "数码", id: 4 }
- ]
- };
- }
- </script>
默认插槽与具名插槽的最终效果
浏览器效果
F12 结构
总结:
使用插槽时, 要让插槽展示对应内容必须在子组件中预留 slot 标签, 并且父组件中要填写 slot 内容.
使用具名插槽时, 父组件中的 tempiate v-slot 值必须对应子组件中 slot 标签上 name 属性值.
如果子组件中有多个默认插槽, 父组件中填写的内容将会被分发到所有的默认插槽, 页面上展示多个父组件内容.
接下来将作用域插槽作为重点:
作用域插槽顾名思义带数据的插槽, 在实际开发过程中, 公用组件的内容一成不变是不可能的, 所以这就要求插槽的内容也是动态数据.
<!-- 子组件中传递数据 --> <template> <div class="hello"> <!-- 作用域插槽 --> <h1 > 这里是作用域插槽 </h1> <slot name="scope" :row="data"></slot> </div> </template> <script> export default { name: "HelloWorld", props: { msg: String }, data() { return { data: [ { name: "哈哈哈", id: 0, age: 1 }, { name: "嘿嘿嘿", id: 1, age: 2 }, { name: "呵呵呵", id: 2, age: 3 }, { name: "啾啾啾", id: 3, age: 4 } ] }; } }; </script> <!-- 父组件中接受, 操作数据 --> <template> <div class="home"> <img alt="Vue logo" src="../assets/logo.png" @click="clickFn" /> <HelloWorld> <!-- 作用域插槽 --> <template slot="scope" slot-scope="scoped"> <div class="text"> <div v-for="item in scoped.row" :key="item.id" @click="scopdeFn(item)" > {{ item.age }} {{ item.name }} </div> </div> </template> </HelloWorld> </div> </template>
作用域插槽的最终效果
image.PNG
image.PNG
以上就是对 vue 插槽的粗鄙理解, 如描述模糊, 理解有误还请群公指正.
点赞就是爱!
来源: http://www.jianshu.com/p/24e4142b3b4b