【译】Vue实用笔记(十一):简单高效滴功能性组件

很多时候,我们都不需要复杂的组件,甚至某些场合我们都不需要组件有自己的state。具体一点呢,就是当你创建一个无逻辑的UI组件的时候。

称符合上面条件的组件为functional components是非常合适的。他们无状态和实体,这就意味着没有自己的实体(所以也就没有办法调用this.$emit 这样的方法)

这些特点让他们变得更加simplefasterlightweight
That makes them simple to reason about, faster and more lightweight.

问题是,什么场景我们才会用到功能性组件呢?简单:就是当这个组件只依赖于props的时候。

例如下面的这个组件:

<template>
  <div>
    <p v-for="item in items" @click="$emit('item-clicked', item)">
      {{ item }}
    </p>
  </div>
</template>

<script>
  export default {
    props: ["items"]
  };
</script>

可以写成这样的功能性组件:

<template functional>
  <div>
    <p v-for="item in props.items" @click="props.itemClick(item);">
      {{ item }}
    </p>
  </div>
</template>

看一下他们两个有什么区别:

  • template标签上添加一个functional属性
  • 属性都可以通过props接收
  • 因为我们不能使用$emit,所以可以把一个函数也定义成属性. 这也正是响应式的框架已经解决了的,并且运行地很好.
  • 不需要<script>部分

想要自己试一下吗?CodeSandbox,来戳我吧

Remember you can read this tip online (with copy/pasteable code), and don’t forget to share VueDose with your colleagues, so they also know about these tips as well!

See you next week.

Alex

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。