什么是插槽?
插槽就是子组件中的提供给父组件使用的一个占位符,用<slot></slot> 表示,父组件可以在这个占位符中填充任何模板代码,如 HTML、组件等,填充的内容会替换子组件的<slot></slot>标签。
具名插槽:<slot name="fruit"></slot>
不具名插槽(默认插槽):<slot></slot>
有A组件和B组件,A组件中使用了B组件,则A组件是B组件的父组件。
A组件中需要使用到B组件的地方:<B></B>
B组件中定义模板,有部分待定的内容可插入slot插槽暂代,然后在A组件中定义。
概念大概是:
A组件:
<A>
<B>
我是填充到A组件插槽中的内容
</B>
</A>
B组件:
<B>
<h1>第一行</h1>
<slot>空着位置,等用到B组件的来填</slot>
<h1>第二行</h1>
</B>
总结:子组件(B)提供模板,中间可有插槽,父组件(A)使用模板组件(B),模板组件间的内容,作为填充到子组件插槽中的内容
作用域插槽
<!DOCTYPE html>
<html lang="zh-en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>插槽作用域</title>
<style>
.current {
color: orange;
}
</style>
</head>
<body>
<div id="app">
<!-- 水果列表 -->
<fruit :list="flist">
<!-- slot-scope是插槽slot传递来的属性的集合 -->
<template slot-scope="slotProps">
<strong v-if="slotProps.info.id==2" class="current">
{{slotProps.info.name}}{{slotProps}}
</strong>
<span v-else>{{slotProps.info.name}}</span>
</template>
</fruit>
</div>
<!-- 引入Vue -->
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
Vue.component('fruit', {
// fruit组件的属性
props: ['list'],
template: `
<div>
<ul>
<li :key="item.id" v-for="item in list" >
<slot :info="item"></slot>
</li>
</ul>
</div>
`,
})
var app = new Vue({
el: '#app',
data: {
flist: [{
id: 1,
name: 'apple',
}, {
id: 2,
name: 'banana',
}, {
id: 3,
name: 'orange',
}],
}
})
</script>
</body>
</html>
运行结果:
slotProps是个对象,用来接收子组件传递来的参数