很多时候,我们都不需要复杂的组件,甚至某些场合我们都不需要组件有自己的state。具体一点呢,就是当你创建一个无逻辑的UI组件的时候。
称符合上面条件的组件为functional components是非常合适的。他们无状态和实体,这就意味着没有自己的实体(所以也就没有办法调用this.$emit
这样的方法)
这些特点让他们变得更加simple、 faster、lightweight。
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