vue的插槽

1. 插槽内容

将 元素作为承载分发内容的出口。

它允许你像这样合成组件:

<navigation-link url="/profile">Your Profile</navigation-link>

<navigation-link> 的模板的实现为:

<a v-bind:href="url" class="nav-link">
    <slot></slot>
</a>

当组件渲染的时候,这个 <slot> 元素将会被替换为“Your Profile”。
插槽内可以包含任何模板代码,包括 HTML:

<navigation-link url="/profile">
    <!-- 添加一个 Font Awesome 图标 -->
    <span class="fa fa-user"></span>
    Your Profile
</navigation-link>

其它的组件:

<navigation-link url="/profile">
    <!-- 添加一个图标的组件 -->
    <font-awesome-icon name="user"></font-awesome-icon>
    Your Profile
</navigation-link>

如果 <navigation-link> 没有包含一个 <slot> 元素,则任何传入它的内容都会被抛弃。

2. 具名插槽

有些时候我们需要多个插槽。这时候 <slot> 元素有一个特殊的特性:name。
例如,一个假设的 <base-layout> 组件的模板如下:

<div class="container">
	<header>
		<slot name="header"></slot>
	</header>
	<main>
		<slot></slot>
	</main>
	<footer>
		<slot name="footer"></slot>
	</footer>
</div>

在向具名插槽提供内容的时候,我们可以在一个父组件的 <template> 元素上使用 slot 特性:

<base-layout>
	<template slot="header">
		<h1>Here might be a page title</h1>
	</template>

	<p>A paragraph for the main content.</p>
	<p>And another one.</p>

	<template slot="footer">
		<p>Here's some contact info</p>
	</template>
</base-layout>

slot 特性的用法也可以直接用在一个普通的元素上:

<base-layout>
	<h1 slot="header">Here might be a page title</h1>

	<p>A paragraph for the main content.</p>
	<p>And another one.</p>

	<p slot="footer">Here's some contact info</p>
</base-layout>

我们还可以保留一个未命名插槽,这个插槽是默认插槽,也就是说它会作为所有未匹配到插槽的内容的统一出口。
上述两个示例渲染出来的 HTML 都将会是:

<div class="container">
	<header>
		<h1>Here might be a page title</h1>
	</header>
	<main>
		<p>A paragraph for the main content.</p>
		<p>And another one.</p>
	</main>
	<footer>
		<p>Here's some contact info</p>
	</footer>
</div>

3. 插槽的默认内容

有的时候为插槽提供默认的内容是很有用的。
例如,一个 <submit-button> 组件可能希望这个按钮的默认内容是“Submit”,但是同时允许用户覆写 为“Save”、“Upload”或别的内容。
可以在组件模板里的 <slot> 标签内部指定默认的内容来做到这一点。

<button type="submit">
    <slot>Submit</slot>
</button>

如果父组件为这个插槽提供了内容,则默认的内容会被替换掉。

4. 编译作用域

若想在插槽内使用数据时,例如:

<navigation-link url="/profile">
    Logged in as {{ user.name }}
</navigation-link>

该插槽可以访问这个模板下的数据。但这个插槽不能访问 <navigation-link> 的作用域。

注意:父组件模板的所有东西都会在父级作用域内编译;子组件模板的所有东西都会在子级作用域内编译。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值