想要传入内容到子层中,slots
是另一种可以选择的方式,在 component
预留空间,父层再放入内容。
节录- Kuro 重新认识 vue.js 中的两句话:
slot
特性是保留一个空间,可以从外部传入内容,而子元件本身对 slot
没有控制权slot
被传了什麽东西以下范例皆取自 When/Why to Use Vue Scoped Slots
子层:
// ChildComponent.vue
<template>
<div>
<slot> Fallback Content </slot>
</div>
</template>
父层:
// ParentComponent.vue
<template>
<child-component>
Override fallback content
</child-component>
</template>
经过编译之後,DOM 的内容如下:
<div> Override fallback content </div>
child-component
标签中的内容Override fallback content
会被置入到 ChildComponent.vue
component 中 slot
的位置
再看另一个例子,在 ArticleHeader
元件中,会显示文章的资讯 (例如: 标题或是描述)
// ArticleHeader.vue
<template>
<div>
<slot v-bind:info="info"> {{ info.title }} </slot>
</div>
</template>
<script>
export default {
data() {
return {
info: {
title: 'title',
description: 'description',
},
}
},
}
</script>
// ParentComponent.vue
<template>
<div>
<article-header />
</div>
</template>
如果在外层也需要显示子层中的 description
的话.....
// 错误
<template>
<div>
<article-header>
{{ info.description }}
</article-header>
</div>
</template>
父层并没有 info 物件, 会报错!!!!
这时候,就可以使用 slots
....
scoped slots
让外层可以取得内层的资料,有两个步骤:
v-bind
让 slot
可使用 info
v-slot
取得 slot 属性// ArticleHeader.vue - Binding Slot Props
<template>
<div>
<slot v-bind:info="info"> {{ info.title }} </slot>
</div>
</template>
v-bind:info="info"
slot prop 将子元件内的状态透过 slot 提供给外层
外层透过 template
和 v-slot
指令
// ParentComponent.vue - using slot props![/images/emoticon/emoticon02.gif](/images/emoticon/emoticon02.gif)
<template>
<div>
<child-component>
<template v-slot="article">
{{ article.info.description }}
</template>
</child-component>
</div>
</template>
附上官网图解:
When/Why to Use Vue Scoped Slots
Summer。桑莫。夏天- Vue.js: Slot
每日一句
很高兴认识你,收集中.....
今天要来说说TypeScript(TS)的模组(Modules), 模组(Modules)定义在一个...
这篇只包含我自己不熟悉的题型,建议有看到文章的人自己做做看题目! 题目来自 六角学院 的 观念测验:...
晚上在看线图的时候,发现铼德2349有几个观点可以提出来跟大家分享。 在今年1月初时,跌破季线,这时...
首先先更新登入的部分,之後会需要登入凭证,这边的一些变数可以再利用 然後是网格交易策略那边,一些参数...
简单的 React 列表范例 const uli = { <li>1</li>...