【Vue.js学习笔记】19:组件的slot插槽,命名slot
学习b站上的小马视频。组件的slot插槽以前学习的组件都只能传入属性,而双标签中没法使用内容,通过添加slot插槽可以使组件能使用其双标签中的内容。添加了slot插槽的组件<template><div>你好,<strong>{{pname}}</strong>!<slot&
·
学习b站上的小马视频。
组件的slot插槽
以前学习的组件都只能传入属性,而双标签中没法使用内容,通过添加slot插槽可以使组件能使用其双标签中的内容。
添加了slot插槽的组件
<template>
<div>
你好,<strong>{{pname}}</strong>!
<slot></slot>
</div>
</template>
<script>
export default {
name: "test_slot",
props: ['pname'],
data() {
return {}
}
}
</script>
<style scoped>
</style>
使用这个组件
<template>
<!--定义了slot插槽时,组件双标签内的内容才有效-->
<test-slot v-bind:pname="123">我是456</test-slot>
</template>
<script>
import test_slot from './test_slot'
export default {
name: "slot_insert",
components: {
'test-slot': test_slot
},
data() {
return {}
}
}
</script>
<style scoped>
</style>
运行结果
命名slot
使用slot标签的name属性为slot命名,这样就可以指定多个可区分的slot,在使用组件时灵活地进行插值。
添加了多个slot插槽的组件
<template>
<!--在组件模板中定义多个slot-->
<div>
<h2>{{tit}}</h2>
<div>
苹果:
<slot name="apple"></slot>
</div>
<div>
香蕉:
<slot name="banana"></slot>
</div>
<div>
橘子:
<slot name="orange"></slot>
</div>
</div>
</template>
<script>
export default {
name: "many_slot",
props: ['tit']
}
</script>
<style scoped>
</style>
使用这个组件
<template>
<!--在使用组件时为多个slot插值-->
<many-slot>
<!--用slot属性指定相应slot的名称-->
<span slot="apple">我是苹果</span>
<span slot="orange">我是橘子</span>
<span slot="banana">我是香蕉</span>
</many-slot>
</template>
<script>
import many_slot from './many_slot'
export default {
name: "slot_insert",
components: {
'many-slot': many_slot
}
}
</script>
<style scoped>
</style>
运行结果
更多推荐
已为社区贡献5条内容
所有评论(0)