向 Vue.js 组件传递多个道具

所有使用基于组件的架构的开发人员,如Vue和React,都知道创建可重复使用的组件是困难的,大多数时候你最终会得到很多优惠,以便更容易从外部控制和自定义组件。

这并不糟糕,但事实是,通过大量的补丁可以变得有点尴尬和丑陋,然而,每个Vue.js组件风格都有办法应对它。

让我们以 vuetify 的按钮组件为例,这是最简单的组件之一。

 1<v-btn
 2  color='primary'
 3  href='https://alligator.io'
 4  small
 5  outline
 6  block
 7  ripple
 8>
 9  Hello Meat
10</v-btn>

将它们放在一个单独的文件中是有意义的,让我们称之为props.js:

1export const buttonProps = {
2  color: 'primary',
3  small: true,
4  outline: true,
5  block: true,
6  ripple: true,
7  href: 'https://alligator.io'
8}

JSX 和 Render 功能

由于它们在渲染时为您提供了更多的力量和灵活性,因此可以轻松地通过多个补丁。

在 Render 功能中:

1import { buttonProps as props } from './props.js';
2
3export default {
4  render: h => h(
5    'v-btn',
6    { props },
7    'Hello Meat'
8  )
9};

在 JSX 中:

1import { buttonProps as props } from './props.js';
2
3const data = { props }
4
5export default {
6  render: h => <v-btn {...data}>Hello Meat</v-btn>
7};

使用 Vue.js 模板

如何使用 Vue.js DSL (或模板)? 不要担心,这也是可能的. 您所需要做的就是使用v-bind指令. 考虑到您必须在您的组件的数据选项中定义的对象,它将绑定所有代理:

 1<template>
 2  <v-btn v-bind='buttonProps'>
 3    Hello Meat
 4  </v-btn>
 5</template>
 6
 7<script>
 8  import { buttonProps } from './props.js';
 9
10  export default {
11    data: () => ({ buttonProps })
12  }
13</script>

借助此技巧,您不必在应用程序中的几个地方填充您的模板,同时仍然可以使用您喜爱的模板标签。

包装上

通过本文中提到的示例可以简化向组件传递多个附件,这对于具有大量附件的演示和第三方组件尤其有用。

请记住,这里使用的例子只是教育性的,如果你想保持DRY(不要重复自己),可能会有更好的方法,取决于具体情况,例如创建自己的包装部件。

Published At
Categories with 技术
Tagged with
comments powered by Disqus