很多時候漱挎,我們都不需要復雜的組件廉涕,甚至某些場合我們都不需要組件有自己的state典蝌。具體一點呢曙砂,就是當你創(chuàng)建一個無邏輯的UI組件的時候。
稱符合上面條件的組件為functional components是非常合適的骏掀。他們無狀態(tài)和實體鸠澈,這就意味著沒有自己的實體(所以也就沒有辦法調(diào)用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>
看一下他們兩個有什么區(qū)別:
- 在
template
標簽上添加一個functional
屬性 - 屬性都可以通過
props
接收 - 因為我們不能使用
$emit
,所以可以把一個函數(shù)也定義成屬性. 這也正是響應式的框架已經(jīng)解決了的坡锡,并且運行地很好. - 不需要
<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