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

2,837 阅读3分钟

前言

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

目前进度[5/22]

原文链接

New v-slot directive in Vue.js 2.6.0

译文

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

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

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

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

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

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

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

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

<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,加载完显示结果,如果有错误显示错误。

结尾

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

其它翻译

1、翻译:提高vue.js中大型数据的性能
2、翻译:测量vue应用运行时的性能!
3、翻译:使用PurgeCSS删除未使用的CSS
4、翻译:Vue.js 2.6.0 中的新指令v-slot
5、翻译:使用v-bind和v-on的自适应组件