原文作者:Alex Jover
译者:程序猿何大叔
特别声明:本文是作者 Alex Jover 发布在 VueDose 上的一个系列。
版权归作者所有。
译者在翻译前已经和作者沟通得到了翻译整个系列的授权。
为了不影响大家阅读,获得授权的记录会放在本文的最后。
很开心见到大家这么喜欢 VueDose 的教程,最近我收到了让我惊讶的关于性能提升的反馈,我非常感激读者们的支持和赞扬 ?。
正文
上周 Vue.js 的 2.6.0-beta.3 版本已经发布,其中包含了进一步简化作用域插槽的新特性。
这篇文章介绍了 vue 的新指令 v-slot
和其简写方式,就如在 RFC-0001 和 RFC-0002 中描述的一样。
为了能够弄清楚它是怎样简化语法的,我们来一起看看它在当前作用域插槽是怎样的。想象一下你有一个 List
组件,并且它暴露了一个过滤后的列表数据作为它的作用域插槽。
你使用该带有作用域插槽的 List
组件应该如下所示:
<template>
<List :items="items">
<template slot-scope="{ filteredItems }">
<p v-for="item in filteredItems" :key="item">{{ item }}</p>
</template>
</List>
</template>
复制代码
我们所要讲解的主要内容与 List
组件的实现方式并没有太大的关系,但是你可以在这个 Codesandbox 查看示例源码。
然而,我们可以直接在组件标签上使用新指令 v-slot
,避免了额外的嵌套:
<template>
<List v-slot="{ filteredItems }" :items="items">
<p v-for="item in filteredItems" :key="item">{{ item }}</p>
</List>
</template>
复制代码
记住 v-slot
指令只能用在组件或 template
标签上,而不能使用在原生 html 标签上。
这种方式能让代码可读性更高,特别是在你有嵌套的作用域插槽,使得难以定位作用域来源的情况下。
v-slot
指令也提供了一个绑定 slot
和 scope-slot
指令的方式,但是需要使用一个 :
来分割它们。举个摘自 vue-promised 的例子:
<template>
<Promised :promise="usersPromise">
<p slot="pending">Loading...</p>
<ul slot-scope="users">
<li v-for="user in users">{{ user.name }}</li>
</ul>
<p slot="rejected" slot-scope="error">Error: {{ error.message }}</p>
</Promised>
</template>
复制代码
以上例子可以使用 v-slot
指令重写如下:
<template>
<Promised :promise="usersPromise">
<template v-slot:pending>
<p>Loading...</p>
</template>
<template v-slot="users">
<ul>
<li v-for="user in users">{{ user.name }}</li>
</ul>
</template>
<template v-slot:rejected="error">
<p>Error: {{ error.message }}</p>
</template>
</Promised>
</template>
复制代码
最后,v-slot
以符号 #
作为其指令的简写模式,上一个例子可以被重写为:
<template>
<Promised :promise="usersPromise">
<template #pending>
<p>Loading...</p>
</template>
<template #default="users">
<ul>
<li v-for="user in users">{{ user.name }}</li>
</ul>
</template>
<template #rejected="error">
<p>Error: {{ error.message }}</p>
</template>
</Promised>
</template>
复制代码
要记住的是,v-slot
指令默认应该简写为 #default
。
读完文章,对于这个新的 slot 语法你感到兴奋吗?
你可以在线阅读这篇 原文,里面有可供复制粘贴的源代码。如果你喜欢这个系列的话,请分享给你的同事们!
结语
此系列的其他文章,会同步系列官网的发布情况,及时地翻译发布到掘金。请持续关注「程序猿何大叔」,相信我会给大家带来更多优质的内容,不要忘了点赞~
如果想要了解译者的更多,请查阅如下:
- 个人博客:blog.hadesz.com
- 个人 github 仓库:github.com/hadeshe93
- 个人微信公众号:搜索「程序猿何大叔」
请求翻译授权记录
觉得本文不错的话,分享一下给小伙伴吧~