Vue 2 官方文档:https://cn.vuejs.org/v2/guide/components-slots.html
Vue 2 示例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Document</title>
</head>
<body>
<div id="app">
<one>
<h1 slot="header">333333</h1>
</one>
</div>
</body>
</html>
<template id="one">
<div>
<slot name="header">默认内容2222</slot>
</div>
</template>
<script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.14/vue.js"></script>
<script>
Vue.component("one", {
template: "#one",
});
var vue = new Vue({
el: "#app",
});
</script>
Vue 3 插槽
具名插槽
父组件
<template>
<div class="about">
<h1>This is an about page</h1>
<hr />
<aboutCom ref="aboutCom">
<template v-slot:header>
<h1>插槽内容</h1>
</template>
</aboutCom>
</div>
</template>
<script>
import aboutCom from "../components/aboutCom.vue";
import aboutComChild from "../components/aboutComChild.vue";
export default {
components: {
aboutCom,
aboutComChild,
},
};
</script>
子组件
<template>
<div>
<h2>这是about的子组件</h2>
<slot name="header">默认内容222222222</slot>
<hr />
<aboutComChild ref="aboutComChild"></aboutComChild>
</div>
</template>
作用域插槽
子组件
<template>
<div>
<slot name="header" :user="userData">{{ userData.name }}</slot>
</div>
</template>
<script>
import aboutComChild from "./aboutComChild.vue";
export default {
components: {
aboutComChild,
},
data() {
return {
userData: { name: "张三", age: 25 },
};
},
};
</script>
父组件
<aboutCom>
<template v-slot:header="slotProps">
<h1>{{ slotProps.user.name }} - {{ slotProps.user.age }}</h1>
</template>
</aboutCom>
简化写法
Vue 3.2+ 支持在模板中使用简化的作用域插槽语法:
<!-- 简化前 -->
<template v-slot:header="slotProps"></template>
<!-- 简化后 -->
<template #header="slotProps"></template>