美文网首页vue.js学习
vuedose.tips(翻译系列十一)

vuedose.tips(翻译系列十一)

作者: 知识文青 | 来源:发表于2019-10-05 17:41 被阅读0次

Simple and performant functional Vue.js components

有时我们不需要复杂的组件,在某些情况下,甚至不需要它们单独拥有一个状态。当构建没有太多逻辑的UI组件时可能就是这种情况。

对于这种情况,功能组件可能非常合适。它们是无状态且无实例的,这意味着它甚至没有一个实例(因此无法调用this.$emit等)

这使他们易于推理,更快,更轻巧。 问题是,什么时候可以使用功能组件?简单:当它们仅依赖 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>

Pay attention to the things that changed:

  • Write functional in the template tag

  • Props are accessible via props

  • Since we don’t have access to $emit, we can use a function as a prop. That’s how the React community has done it the whole time and it worked pretty well.

  • No need for the script part

Do you want to see it in action? Check it out yourself in thisCodeSandbox!

相关文章

网友评论

    本文标题:vuedose.tips(翻译系列十一)

    本文链接:https://www.haomeiwen.com/subject/tycypctx.html