插槽的理解
插槽就是子组件中的提供给父组件使用的一个占位符,用<slot></slot>表示,父组件可以在这个占位符中填充任何模板代码,如HTML、组件等,填充的内容会替换子组件的<slot></slot>标签。
vue的slot主要分三种,默认插槽,具名插槽,作用域插槽;
- 默认插槽
// 它允许你像这样合成组件
// 父组件
<navigation-link url="/profile">
your profile
</navigation-link>
//然后你在<navigation-link>的模板可能会写为:
子组件
<a :href="url" class="nav-link">
<slot></slot>
</a>
父组件渲染出
<a :href="url" class="nav-link">
your profile
</a>
2. 具名插槽
什么是具名插槽,其实就是再子组件中定义插槽是,给对应的插槽分别起个名字,方便插入父组件将内容根据name来填充对应的内容。
// 子组件中,定义两个具名插槽:
<div class="container">
<header>
<slot name="header"></slot>
</header>
// main和nav相当于都是默认插槽
<main>
<slot></slot>
</main>
<nav>
<slot name="default></slot>
</nav>
<footer>
<slot name="footer"></slot>
</footer>
</div>
// 父组件
// 为了验证,子组件中的插槽可以填充任何结构的内容,所以我这边专门在one_slot插槽中插入一个组件,而在two插槽就单纯插入一串普通的数据
<base-layout>
<template v-slot:header>
<h1>Here might be a page title</h1>
</template>
// 一个不带 name 的 <slot> 出口会带有隐含的名字“default”。
<p>A paragraph for the content.</p>
<p>And another one.</p>
// 简写
<template #footer>
<p>Here's some contact info</p>
</template>
</base-layout>
父组件渲染出
<div class="container">
<header>
<h1>Here might be a page title</h1>
</header>
<main>
<p>A paragraph for the content.</p>
<p>And another one.</p>
</main>
<nav>
<p>A paragraph for the content.</p>
<p>And another one.</p>
</nav>
<footer>
<p>Here's some contact info</p>
</footer>
</div>
// 跟 v-on 和 v-bind 一样,v-slot 也有缩写,即把参数之前的所有内容 (v-slot:) 替换为字符 #。例如 v-slot:header 可以被重写为 #header:
3.作用域插槽
在封装组件的过程中,可以为预留的 插槽绑定 props 数据(除了name),这种带有 props 数数据的 叫做“作用域插槽"
// 子组件
<template>
<div class="child">
<h3>这里是子组件</h3>
<slot name="demo" :text="account" :record="user"></slot>
</div>
</template>
<script>
export default {
name:"child",
data(){
return {
user: ['张三','李四',"王五"],
account:"ray"
}
}
}
</script>
// 父组件
<template>
<div class="father">
<child>
<template #demo="{text,record}">
{{text}}
<div v-for="item in record" :key="item">{{item}}</div>
</template>
</child>
</div>
</template>
父组件渲染
<div class="father">
<div class="child">
<h3>这里是子组件</h3>
ray
<div>张三</div>
<div>李四</div>
<div>王五</div>
</div>
</div>