浅谈Vue 函数式组件的使用技巧
什么是函数式组件
没有管理任何状态,也没有监听任何传递给它的状态,也没有生命周期方法,它只是一个接受一些 prop 的函数。简单来说是 一个无状态和无实例的组件
基本写法:
Vue.component(’my-component’, { functional: true, // Props 是可选的 props: { // ... }, // 为了弥补缺少的实例 // 提供第二个参数作为上下文 render: function(createElement, context) { // ... }})
.vue 单文件组件写法
<template functional> ...</template>
因为函数式组件没有 this,参数就是靠 context 来传递的了,有如下字段的对象:
props:提供所有 prop 的对象 children:VNode 子节点的数组 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.staticClass 则是绑定内联样式TitleView.vue
<template functional> <div : :style='data.staticStyle'> <h1>{{ props.title }}</h1> </div></template>
Test.vue
<template> <title-view : /></template>
component 组件引入
函数式组件引入其他组件方式如下,具体参考:github.com/vuejs/vue/i…
<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>
总结
虽然速度和性能方面是函数式组件的优势、但不等于就可以滥用,所以还需要根据实际情况选择和权衡。比如在一些展示组件。例如, buttons, tags, cards,或者页面是静态文本,就很适合使用函数式组件。
到此这篇关于浅谈Vue 函数式组件的使用技巧的文章就介绍到这了,更多相关Vue 函数式组件内容请搜索好吧啦网以前的文章或继续浏览下面的相关文章希望大家以后多多支持好吧啦网!
相关文章:
