翻译:Vue.js 2.6.0 中的新指令v-slot

前言

为了提升英文水平,尝试着翻译一些英文技术文章,首先就从这个Vue的小技巧文章开始,目前英文版一共22篇。计划用时2~3个月翻译完成。html

目前进度[5/22]vue

原文连接

New v-slot directive in Vue.js 2.6.0git

译文

我很高兴看到人们喜欢VueDose!我收到了关于前面发布的性能文章的惊人反馈!很是感谢你的支持和赞美!github

上周发布了Vue.js的版本2.6.0-beta.3,启用新的功能可以进一步简化做用域插槽。promise

它引入了新的v-slot指令及其简写,如RFC-0001RFC-0002中所述。dom

为了理解它是如何简化语法的,让咱们看一下目前做用域插槽的使用。假如你有一个列表组件,打算把筛选后的数据暴露给scope。post

你使用做用域插槽处理数据的方式像是:性能

<template>
  <List :items="items">
    <template slot-scope="{ filteredItems }">
      <p v-for="item in filteredItems" :key="item">{{ item }}</p>
    </template>
  </List>
</template>
复制代码

这里没有列表组件相关的实现,可是你能够在this Codesandbox 中查看这个例子。this

使用v-slot,你能够直接把做用域插槽直接写在组件上,从而避免了额外的dom:spa

<template>
  <List v-slot="{ filteredItems }" :items="items">
    <p v-for="item in filteredItems" :key="item">{{ item }}</p>
  </List>
</template>
复制代码

记住,v-slot只能在组件和模板上使用,不能在纯html标签上使用。

这样写使得代码具备更多的可读性,特别是当你嵌套使用做用域插槽时,你会很难弄解释做用域插槽的数据来源。

v-slot指令还引入了一种组合slot和scoped slots指令的方法,可是要加上冒号

例如,这个例子来自于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的简写是#

你对这个新的slot的语法感到兴奋吗?

你能够在线阅读文章tip online(能够 复制/粘贴 代码),可是请你记住,若是你喜欢,要和全部同事分享VueDose

下周见。

个人理解

当你写组件的时候,可使用v-slot代替slotslot-scope,可以简化代码和代码的复杂度,可以更加清晰明白的追踪数据。

vue-promisedgithub开源项目,主要的做用是,在你加载数据的时候,在加载的过程当中显示loding,加载完显示结果,若是有错误显示错误。

结尾

水平有限,不免有错漏之处,望各位大大轻喷的同时可以指出,跪谢!

其它翻译

一、翻译:提升vue.js中大型数据的性能
二、翻译:测量vue应用运行时的性能!
三、翻译:使用PurgeCSS删除未使用的CSS
四、翻译:Vue.js 2.6.0 中的新指令v-slot
五、翻译:使用v-bind和v-on的自适应组件

相关文章
相关标签/搜索