做者:David Desmaisons翻译:疯狂的技术宅javascript
原文:https://alligator.io/vuejs/re...html
未经容许严禁转载前端
在本文中咱们讨论 Vue 中的无渲染插槽模式可以帮助解决哪些问题。vue
在 Vue.js 2.3.0 中引入的做用域插槽显著提升了组件的可重用性。无渲染组件模式应运而生,解决了提供可重用行为和可插入表示的问题。java
在这里,咱们将会看到如何解决相反的问题:怎样提供可重用的外观和可插入的行为。node
这种模式适用于实现复杂行为且具备可自定义表示的组件。git
它知足如下功能:程序员
举个例子:一个执行 Ajax 请求并显示结果的插槽的组件。组件处理 Ajax 请求并加载状态,而默认插槽提供演示。github
这是一个简化版的实现:面试
<template> <div> <slot v-if="loading" name="loading"> <div>Loading ...</div> </slot> <slot v-else v-bind={data}> </slot> </div> </template> <script> export default { props: ["url"], data: () => ({ loading: true, data: null }), async created() { this.data = await fetch(this.url); this.loading = false; } }; </script>
用法:
<lazy-loading url="https://server/api/data"> <template #default="{ data }"> <div>{{ data }}</div> </template> </lazy-loading>
有关这种模式的原始文章,请在这里查看。
若是问题反过来该怎么办:想象一下,若是一个组件的主要特征就是它的表示形式,另外它的行为应是可自定义的。
假设你想要基于 SVG 建立一个树组件,以下所示:
你想要提供 SVG 的显示和行为,例如在单击时收回节点和突出显示文本。
当你打算不对这些行为进行硬编码,而且让组件的用户自由覆盖它们时,就会出现问题。
暴露这些行为的简单解决方案是向组件添加方法和事件。
你可能会这样去实现:
<script> export default { mounted() { // pseudo code nodes.on('click',(node) => this.$emit('click', node)); }, methods: { expandNode(node) { //... }, retractNode(node) { //... }, highlightText(node) { //... }, } }; </script>
若是组件的使用者要向组件添加行为,须要在父组件中使用 ref,例如:
<template> <tree ref="tree" @click="onClick"></tree> </template> <script> export default { methods: { onClick(node) { this.$refs.tree.retractNode(node); } } }; </script>
这种方法有几个缺点:
让咱们看看无渲染插槽如何解决这些问题。
行为基本上包括证实对事件的反应。因此让咱们建立一个插槽,用来接收对事件和组件方法的访问:
<template> <div> <slot name="behavior" :on="on" :actions="actions"> </slot> </div> </template> <script> export default { methods: { expandNode(node) { }, retractNode(node) { }, //... }, computed:{ actions() { const {expandNode, retractNode} = this; return {expandNode, retractNode}; }, on() { return this.$on.bind(this); } } }; </script>
on
属性是父组件的 $on
方法,所以能够监听全部事件。
能够将行为实现为无渲染组件。接下来编写点击扩展组件:
export default { props: ['on','action'] render: () => null, created() { this.on("click", (node) => { this.actions.expandNode(node); }); } };
用法:
<tree> <template #behavior="{ on, actions }"> <expand-on-click v-bind="{ on, actions }"/> </template> </tree>
该解决方案的主要优势是:
例如,经过将图形组件声明为:
<template> <div> <slot name="behavior" :on="on" :actions="actions"> <expand-on-click v-bind="{ on, actions }"/> </slot> </div> </template>
考虑一个悬停突出显示组件:
export default { props: ['on','action'] render: () => null, created() { this.on("hover", (node) => { this.actions.highlight(node); }); } };
覆盖标准行为:
<tree> <template #behavior="{ on, actions }"> <highlight-on-hover v-bind="{ on, actions }"/> </template> </tree>
添加两个预约义的行为:
<tree> <template #behavior="{ on, actions }"> <expand-on-click v-bind="{ on, actions }"/> <highlight-on-hover v-bind="{ on, actions }"/> </template> </tree>
做为行为的组件是可以自描述的。
on
属性能够访问全部组件事件。默认状况下,该插槽可以使用新事件。
无渲染插槽提供了一种有趣的解决方案,能够在组件中公开方法和事件。它们提供了更具可读性和可重用性的代码。
能够在 github 上找到实现此模式的树组件的代码:Vue.D3.tree