vue2 插槽20 slot 作用域插槽 具名插槽
vue 官方规定:每一个 slot 插槽,都要有一个 name 名称
如果省略了 slot 的 name 属性,则有一个默认名称叫做 default
组件中使用:
<slot name="default"> <h6>这是 default 插槽的后备内容</h6> </slot>
省略后:
<slot>
<h6>这是 default 插槽的后备内容</h6>
</slot>
app中使用:
<Left>
<template #defaul>
<p>这是在 Left 组件的内容区域,声明的 p 标签</p>
</template>
</Left>
作用域插槽 具名插槽:
app:
<template>
<div class="app-container">
<h1 v-color="color">App 根组件</h1>
<p v-color="'red'">测试</p>
<button @click="color = 'green'">改变 color 的颜色值</button>
<hr />
<Left>
<template #def>
<p>这是在 Left 组件的内容区域,声明的 p 标签</p>
</template>
</Left>
<Article>
<template #title>
<h3>一首诗</h3>
</template>
<template #content="{ msg, user }">
<div>
<p>字</p>
<p>{{ msg }}</p>
<p>{{ user.name }}</p>
<p>{{ user.age }}</p>
</div>
</template>
<template #author>
<div>文采呱呱</div>
</template>
</Article>
<hr />
<div class="box" style="display: none;">
<!-- 渲染 Left 组件和 Right 组件 -->
<Left>
<!-- 默认情况下,在使用组件的时候,提供的内容都会被填充到名字为 default 的插槽之中 -->
<!-- 1. 如果要把内容填充到指定名称的插槽中,需要使用 v-slot: 这个指令 -->
<!-- 2. v-slot: 后面要跟上插槽的名字 -->
<!-- 3. v-slot: 指令不能直接用在元素身上,必须用在 template 标签上 -->
<!-- 4. template 这个标签,它是一个虚拟的标签,只起到包裹性质的作用,但是,不会被渲染为任何实质性的 html 元素 -->
<!-- 5. v-slot: 指令的简写形式是 # -->
<template #defaul>
<p>这是在 Left 组件的内容区域,声明的 p 标签</p>
</template>
</Left>
</div>
</div>
</template>
<script>
import Left from '@/components/Left.vue'
import Article from '@/components/Article.vue'
export default {
data() {
return {
color: 'blue'
}
},
components: {
Left,
Article
},
// 私有自定义指令的节点
directives: {
// 定义名为 color 的指令,指向一个配置对象
/* color: {
// 当指令第一次被绑定到元素上的时候,会立即触发 bind 函数
// 形参中的 el 表示当前指令所绑定到的那个 DOM 对象
bind(el, binding) {
console.log('触发了 v-color 的 bind 函数')
el.style.color = binding.value
},
// 在 DOM 更新的时候,会触发 update 函数
update(el, binding) {
console.log('触发了 v-color 的 update 函数')
el.style.color = binding.value
}
} */
color(el, binding) {
el.style.color = binding.value
}
}
}
</script>
<style lang="less">
.app-container {
padding: 1px 20px 20px;
background-color: #efefef;
}
.box {
display: flex;
}
</style>
文章页:
<template>
<div class="article-container">
<h3 v-color="'red'">Article 组件</h3>
<!-- 文章的标题 -->
<div class="header-box">
<slot name="title"></slot>
</div>
<!-- 文章的内容 -->
<div class="content-box">
<!-- 在封装组件时,为预留的 <slot> 提供属性对应的值,这种用法,叫做 “作用域插槽” -->
<slot name="content" msg="hello vue.js11111" :user="userinfo"></slot>
</div>
<!-- 文章的作者 -->
<div class="footer-box">
<slot name="author"></slot>
</div>
</div>
</template>
<script>
export default {
// 首字母要大写
name: 'Article',
data() {
return {
// 用户的信息对象
userinfo: {
name: 'zs',
age: 20
}
}
}
}
</script>
<style lang="less" scoped>
.article-container {
> div {
min-height: 150px;
}
.header-box {
background-color: pink;
}
.content-box {
background-color: lightblue;
}
.footer-box {
background-color: lightsalmon;
}
}
</style>
代码改变了我们,也改变了世界

浙公网安备 33010602011771号