vue.js 中什么是插槽? 有什么用?
插槽就是子组件中的提供给父组件使用的一个占位符, 用 < slot></slot> 表示, 父组件可以在这个占位符中填充任何模板代码, 如 html, 组件等, 填充的内容会替换子组件的 < slot></slot > 标签.
插槽用于决定将所携带的内容, 插入到指定的某个位置, 从而使模板分块, 具有模块化的特质和更大的重用性. 插槽显不显示, 怎样显示是由父组件来控制的, 而插槽在哪里显示就由子组件来进行控制.
插槽的基本使用方式
子组件模板中使用 < slot></slot > 后, 父组件模板调用子组件的标签中所写的内容即可把这个 slot 替换掉
子组件模板中 < slot > 默认的渲染模板 </slot> 标签之间的内容为默认内容.
- <div id="app">
- <child-item></child-item>
- <child-item > 用户自定义的内容 </child-item>
- </div>
- <script src="./js/vue.js"></script>
- <script>
- Vue.component("child-item", {
- template: `
- <div>
- <slot > 默认的渲染模板 </slot>
- </div>
- `
- });
- const vm = new Vue({
- el: "#app"
- });
- </script>
具名插槽的使用方式
为 < slot><slot > 添加 name 属性, 定义一个名字 例如: <slot name="head"> 默认的头部信息 </slot>
在使用时,<template v-slot:head> <div style="background: blue;"> 网页头部 </div> </template>, 通过 v-slot:name 来指定 template 内部的内容去替换哪个插槽,
注意: v-slot 是 Vue2.6.0 以上版本新增的标签, 并且只能在 template 标签中使用
- <div id="app">
- <child-item></child-item>
- <child-item>
- <template v-slot:head>
- <div style="background: blue;"> 网页头部 </div>
- </template>
- <template v-slot:main>
- <div style="background: grey;"> 网站主体内容区域 </div>
- </template>
- <template v-slot:foot>
- <div style="background: orange;"> 网站脚注区域 </div>
- </template>
- </child-item></div><script src="./js/vue.js"></script><script>
- Vue.component("child-item", {
- template: ` <div>
- <slot name="head"> 默认的头部信息 </slot>
- <slot name="main"> 默认的主体内容信息 </slot>
- <slot name="foot"> 默认的网站脚注信息 </slot>
- </div>
- `
- });
- const vm = new Vue({
- el: "#app"
- });</script>
作用域插槽的使用方式
作用域插槽为用户提供了自定义数据显示效果的方式
在 < slot></slot > 标签上添加的属性, 例如: <slot a="1" b="2"></slot>
那么在使用该组件时, 可以使用 <template v-slot="{ a, b }"></template>, 接收到对应 a b 的值
<div id="app"> <movie-list :movies="movies"> <!-- 在组件调用标签内, 使用 template 标签, 借助 v-slot 指令接收数据 --> <template v-slot="{ movie, index }"> <h1> {{ index }} -- {{ movie }}</h1> </template> </movie-list> <movie-list :movies="movies"></movie-list> </div> <script src="./js/vue.js"></script> <script> const movieList = { template: ` <ul> <li v-for="(item, index) in movies" :key="index"> // 在插槽上暴露数据 movie 和 index <slot :movie="item" :index="index">{{ item }}</slot> </li> </ul> `, props: { movies: Array } } Vue.component("movie-list", movieList); const vm = new Vue({ el: "#app", data: { movies: ["电影列表 1", "电影列表 2", "电影列表 3", "电影列表 4", "电影列表 5" ] } }); </script>
更多 web 前端开发 https://www.html.cn/ 知识, 请查阅 HTML 中文网 !!
来源: http://www.css88.com/qa/vue-js/17197.html