Vue 函数式组件的使用技巧__Vue.js
发布于 4 年前 作者 banyungong 2565 次浏览 来自 分享
粉丝福利 : 关注VUE中文社区公众号,回复视频领取粉丝福利

什么是函数式组件 没有管理任何状态,也没有监听任何传递给它的状态,也没有生命周期方法,它只是一个接受一些 prop 的函数。简单来说是 一个无状态和无实例的组件

基本写法:

Vue.component('my-component', {
  functional: true,
  // Props 是可选的
  props: {
    // ...
  },
  // 为了弥补缺少的实例
  // 提供第二个参数作为上下文
  render: function(createElement, context) {
    // ...
  }
})

.vue 单文件组件写法

<template functional>
  ...
</template>

因为函数式组件没有 this,参数就是靠 context 来传递的了,有如下字段的对象:

  • props:提供所有 prop 的对象
  • childrenVNode 子节点的数组
  • slots:一个函数,返回了包含所有插槽的对象
  • scopedSlots:(2.6.0+) 一个暴露传入的作用域插槽的对象。也以函数形式暴露普通插槽。
  • data:传递给组件的整个数据对象,作为 createElement 的第二个参数传入组件
  • parent:对父组件的引用
  • listeners:(2.3.0+) 一个包含了所有父组件为当前组件注册的事件监听器的对象。这是 data.on 的一个别名。
  • injections:(2.3.0+) 如果使用了 inject 选项,则该对象包含了应当被注入的 property。

使用技巧

以下总结、都是基于使用 <template> 标签开发函数式组件中遇到的问题

attr 与 listener 使用

平时我们在开发组件时,传递 prop 属性以及事件等操作,都会使用v-bind="$attrs"v-on="$listeners"。而在函数式组件的写法有所不同,attrs属性集成在 data中。

<template functional>
  <div v-bind="data.attrs" v-on="listeners">
    <h1>{{ props.title }}</h1>
  </div>
</template>

class 与 style 绑定

在引入函数式组件、直接绑定外层的class类名和style样式是无效的。data.class 表示动态绑定class, data.staticClass 则表示绑定静态class, data.staticStyle 则是绑定内联样式

TitleView.vue

<template functional>
  <div :class="[data.class, data.staticClass]" :style="data.staticStyle">
    <h1>{{ props.title }}</h1>
  </div>
</template>

Test.vue

<template>
  <title-view
    :class="{title-active: isActive}"
    style="{ color: red }"
    title="Hello Do"
  />
</template>

component 组件引入

函数式组件引入其他组件方式如下,具体参考:https://github.com/vuejs/vue/issues/7492#issuecomment-379570456

<template functional>
  <div class="tv-button-cell">
    <component :is="injections.components.TvButton" type="info" />
    {{ props.title }}
    </component>
  </div>
</template>

<script>
import TvButton from '../TvButton'

export default {
  inject: {
    components: {
      default: {
        TvButton
      }
    }
  }
}
</script>

$options 计算属性

有时候需要修改prop数据源, 使用 Vue 提供的 $options 属性,可以访问这个特殊的方法。

<template functional>
  <div v-bind="data.attrs" v-on="listeners">
    <h1>{{ $options.upadteName(props.title) }}</h1>
  </div>
</template>

<script>
  export default {
    updateName(val) {
      return 'hello' + val
    }
  }
</script>

总结

虽然速度和性能方面是函数式组件的优势、但不等于就可以滥用,所以还需要根据实际情况选择和权衡。比如在一些展示组件。例如, buttonstags, cards,或者页面是静态文本,就很适合使用函数式组件。

版权声明:著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。 作者: 稻草叔叔 原文链接:https://juejin.im/post/6844904191677186061

回到顶部