Vue从入门到实战:函数式组件

来自CloudWiki
跳转至: 导航搜索

什么是函数式组件

之前创建的锚点标题组件是比较简单,没有管理任何状态,也没有监听任何传递给它的状态,也没有生命周期方法。实际上,它只是一个接受一些 prop 的函数。在这样的场景下,我们可以将组件标记为 functional,这意味它无状态 (没有响应式数据),也没有实例 (没有 this 上下文)。一个函数式组件就像这样:

Vue.component('my-component', {
  functional: true,
  // Props 是可选的
  props: {
    // ...
  },
  // 为了弥补缺少的实例
  // 提供第二个参数作为上下文
  render: function (createElement, context) {
    // ...
  }
})
  • 注意:在 2.3.0 之前的版本中,如果一个函数式组件想要接收 prop,则 props 选项是必须的。在 2.3.0 或以上的版本中,你可以省略 props 选项,所有组件上的 attribute 都会被自动隐式解析为 prop。当使用函数式组件时,该引用将会是 HTMLElement,因为他们是无状态的也是无实例的。
  • 在 2.5.0 及以上版本中,如果你使用了单文件组件,那么基于模板的函数式组件可以这样声明:
<template functional>
</template>

组件的context参数

组件需要的一切都是通过 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。

在添加 functional: true 之后,需要更新我们的锚点标题组件的渲染函数,为其增加 context 参数,并将 this.$slots.default 更新为 context.children,然后将 this.level 更新为 context.props.level。

因为函数式组件只是函数,所以渲染开销也低很多。

函数式组件的应用

改进版案例

利用函数式组件,我们将上一节的例子更改如下:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<script src="vue.js"></script>
	</head>
	<body>
		
		<div id="app">
			<anchored-heading :level="3">
				Hello world!
			</anchored-heading>
		</div>
		<script type = "text/javascript">
			var getChildrenTextContent = function (children) {
			  return children.map(function (node) {
			    return node.children
			      ? getChildrenTextContent(node.children)
			      : node.text
			  }).join('')
			}

			Vue.component('anchored-heading', {
				functional: true,
			  render: function (createElement, context) {
			    // 创建 kebab-case 风格的 ID
			    var headingId = getChildrenTextContent(context.children)
			      .toLowerCase()
			      .replace(/\W+/g, '-')
			      .replace(/(^-|-$)/g, '')
			    
			    return createElement(
			      'h' + context.props.level,
			      [
			        createElement('a', {
			          attrs: {
			            name: headingId,
			            href: '#' + headingId
			          }
			        }, context.slots().default)
			      ]
			    )
			  },
			  props: {
			    level: {
			      type: Number,
			      required: true
			    }
			  }
			})
			new Vue({
			  el: '#app'
			})
		</script>
	</body>
</html>

包装组件

在作为包装组件时它们也同样非常有用。比如,当你需要做这些时:

  • 程序化地在多个组件中选择一个来代为渲染;
  • 在将 children、props、data 传递给子组件之前操作它们。
<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<script src="vue.js"></script>
		<style>
			.menu{
				margin:0; 
				padding:0; 
				height:30px; 
			}
			.menu li{
				float:left;
				width:100px;
				background-color:black;
				text-align:center;
				padding:5px;
				list-style-type:none;
			}
			.menu td{
				width:100px;
				background-color:black;
				text-align:center;
				padding:5px;
			}
			
			.menu li a, .menu td a{
				color:white; 
				text-decoration:none; 
				font-size:12px;
			}
			.menu li a:hover, .menu td a:hover{
				color:yellow;
			}
		</style>
	</head>
	<body>
		
		<div id="app">
			<layout-menu :items="menus" kind="ul"></layout-menu>
		</div>
		<script>
			let TableMenu = Vue.extend({
				props: {
					menus: {
						type: Array,
						required: true
					}
				},
	      template: `
	      	<table class="menu">
	      		<tr>
	      			<td v-for="menu in menus">
	      				<a :href="menu.url">{{menu.name}}</a>
	      			</td>
	      		</tr>
	      	</table>
	      `
  		});
  		
  		let UlMenu = Vue.extend({
				props: {
					menus: {
						type: Array,
						required: true
					}
				},
	      template: `
	      	<ul class="menu">
      			<li v-for="menu in menus">
      				<a :href="menu.url">{{menu.name}}</a>
      			</li>
	      	</ul>
	      `
  		});
  		
  		Vue.component('layout-menu', {
			  functional: true,
			  props: {
			    items: {
			      type: Array,
			      required: true
			    },
			    kind: {
			    	type: String,
			    	default: 'ul'
			    }
			  },
			  render: function (createElement, context) {
			    function appropriateMenuComponent () {
			    	// 根据kind prop的值来选择要渲染的组件
			      if (context.props.kind === 'ul')  return UlMenu;
			      else return TableMenu;
			    }
					
			    return createElement(
			      appropriateMenuComponent(),
			      // 将布局组件的items prop传给子组件的menus prop
			      // 并使用展开运算符将数据对象一起传进去
			      {props: {'menus': context.props.items}, ...context.data},
			      context.children
			    )
			  }
			})
			
			new Vue({
			  el: '#app',
			  data: {
			  	menus: [
			  		{name: '新浪新闻', url: '#'},
			  		{name: '网易游戏', url: '#'},
			  		{name: '百度搜索', url: '#'}
			  	]
			  }
			})
		</script>
	</body>
</html>

向子元素或子组件传递 attribute 和事件

在普通组件中,没有被定义为 prop 的 attribute 会自动添加到组件的根元素上,将已有的同名 attribute 进行替换或与其进行智能合并。

然而函数式组件要求你显式定义该行为:

Vue.component('my-functional-button', {
  functional: true,
  render: function (createElement, context) {
    // 完全透传任何 attribute、事件监听器、子节点等。
    return createElement('button', context.data, context.children)
  }
})

通过向 createElement 传入 context.data 作为第二个参数,我们就把 my-functional-button 上面所有的 attribute 和事件监听器都传递下去了。事实上这是非常透明的,以至于那些事件甚至并不要求 .native 修饰符。

如果你使用基于模板的函数式组件,那么你还需要手动添加 attribute 和监听器。因为我们可以访问到其独立的上下文内容,所以我们可以使用 data.attrs 传递任何 HTML attribute,也可以使用 listeners (即 data.on 的别名) 传递任何事件监听器。

<template functional>
  <button
    class="btn btn-primary"
    v-bind="data.attrs"
    v-on="listeners"
  >
    <slot/>
  </button>
</template>

slots() 和 children 对比

你可能想知道为什么同时需要 slots() 和 children。slots().default 不是和 children 类似的吗?在一些场景中,是这样——但如果是如下的带有子节点的函数式组件呢?

<my-functional-component>
  <p v-slot:foo>
    first
  </p>
  <p>second</p>
</my-functional-component>

对于这个组件,children 会给你两个段落标签,而 slots().default 只会传递第二个匿名段落标签,slots().foo 会传递第一个具名段落标签。同时拥有 children 和 slots(),因此你可以选择让组件感知某个插槽机制,还是简单地通过传递 children,移交给其它组件去处理。