之前接触过 Vue 的组件、父子传递、插槽等内容,但不是特别清晰,现在花一些时间整理一下,以最简单的例子回顾学习内容
Vue 组件封装简单案例——小白入门
Vue 子传父案例简单入门——小白推荐
Vue 父传子案例简单入门
Vue 中使用 Echarts 简单入门——小白必看
vue-quill-editor 富文本编辑器在 Vue 中最简单使用
这篇文章主要介绍插槽的使用小案例
新建 Vue 项目,以 default (babel, eslint) 模式进行安装,删除 Helloworld.vue 相关代码,新建 SlotTest.vue,
SlotTest.vue
<template>
<div>
App.vue 会将 Slot 标签里的内容传递过来:
<slot></slot>
</div>
</template>
<script>
export default {
name: "SlotTest"
}
</script>
<style scoped>
</style>
在 App.vue 中引入 SlotTest.vue, 并在 SlotTest标签内写好要传递的内容,
App.vue
<template>
<div id="app">
<SlotTest>
<h1>我写在App.vue里面</h1>
</SlotTest>
</div>
</template>
<script>
import SlotTest from "./components/SlotTest";
export default {
name: 'App',
components: {
SlotTest
}
}
</script>
<style>
</style>
运行结果如图所示:
在此基础上,对具名插槽进行展示,SlotTest.vue 中需要定义 slot 的 name,
SlotTest.vue
<template>
<div>
App.vue 会将 Slot 标签里的内容传递过来
<slot name="header"></slot>
<slot></slot>
</div>
</template>
<script>
export default {
name: "SlotTest"
}
</script>
<style scoped>
</style>
在 App.vue 中引用相应的 name,写在 template 标签里
App.vue
<template>
<div id="app">
<SlotTest>
<!-- 具名插槽 -->
<template v-slot:header>
<h1>我是具名插槽</h1>
</template>
<h1>我写在App.vue里面</h1>
</SlotTest>
</div>
</template>
<script>
import SlotTest from "./components/SlotTest";
export default {
name: 'App',
components: {
SlotTest
}
}
</script>
<style>
</style>