vuedose.tips(系列翻译四)

New v-slot directive in Vue.js 2.6.0

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

It introduces the newv-slotdirective and its shorthand, as described in theRFC-0001andRFC-0002.

为了了解它如何简化语法,让我们看看它在当前作用域插槽中的表现。想象一下,您有一个List组件,该组件公开了一个过滤列表作为其作用域

这跟使用该列表作用域插槽的方式类似:

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

The implementation of the List component is not too relevant, but inthis Codesandboxyou can check an example of it.

使用v-slot,您可以直接在component标签上写入该插槽的范围,从而避免了额外的层

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

请注意,v-slot 只能用于组件和模板标签,而不能用于纯HTML标签

这样,在嵌套作用域插槽时,代码特别易于阅读,这可能很难推断出作用域的来源。

v-slot指令还引入了一种组合插槽和scoped-slots指令的方法,但是要用冒号:将它们分开

<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。 您对这种新的插槽语法感到兴奋吗?

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • Vue 实例 属性和方法 每个 Vue 实例都会代理其 data 对象里所有的属性:var data = { a:...
    云之外阅读 2,388评论 0 6
  • 组件(Component)是可复用的Vue实例,这句话给了我们两个信息,可复用和Vue实例。可复用就是能够重复使用...
    书上得来终觉浅阅读 371评论 0 0
  • 主要还是自己看的,所有内容来自官方文档。 介绍 Vue.js 是什么 Vue (读音 /vjuː/,类似于 vie...
    Leonzai阅读 3,556评论 0 25
  • 以下内容是我在学习和研究Vue时,对Vue的特性、重点和注意事项的提取、精练和总结,可以做为Vue特性的字典; 1...
    科研者阅读 14,226评论 3 24
  • 什么是组件? 组件 (Component) 是 Vue.js 最强大的功能之一。组件可以扩展 HTML 元素,封装...
    youins阅读 9,709评论 0 13

友情链接更多精彩内容