18

将多个属性传递给 Vue 组件的几种方式

 4 years ago
source link: http://developer.51cto.com/art/202004/614086.htm
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

所有使用基于组件的体系结构(如Vue和React)的开发人员都知道,创建可重用组件是很困难的,而且大多数情况下,最终会通过传入大量的属性,以便从外部更容易地控制和自定义组件。这并不坏,但是传递大量属性确实会变得有点麻烦和丑陋。

BVFvy2q.jpg!web

我们以 vuetify 的按钮组件为例,它是最简单的组件之一。假设我们想要在大多数情况下传递相同的属性:

<v-btn 
  color='primary' 
  href='https://alligator.io' 
  small 
  outline 
  block 
  ripple 
> 
  Hello Meat 
</v-btn> 

将它们放在单独的文件中是有意义的,这个文件我们取名为props.js

export const buttonProps = { 
  color: 'primary', 
  small: true, 
  outline: true, 
  block: true, 
  ripple: true, 
  href: 'https://alligator.io' 
} 

JSX 和 render 函数

由于JSX 和 render 函数在渲染时为我们提供了更多的功能和灵活性,所以一次传递多个属性是相当容易的。

在 render 函数中:

import { buttonProps as props } from './props.js'; 
 
export default { 
  render: h => h( 
    'v-btn', 
    { props }, 
    'Hello Meat' 
  ) 
}; 

在 JSX 中:

import { buttonProps as props } from './props.js'; 
 
const data = { props } 
 
export default { 
  render: h => <v-btn {...data}>Hello Meat</v-btn> 
}; 

使用 Vue.js 模板

使用Vue template怎么样?不用担心,那也是可能的。我们所需要做的就是使用v-bind指令。对于必须在组件的data选项中定义的对象,它将绑定所有属性

<template> 
  <v-btn v-bind='buttonProps'> 
    Hello Meat 
  </v-btn> 
</template> 
 
<script> 
  import { buttonProps } from './props.js'; 
 
  export default { 
    data: () => ({ buttonProps }) 
  } 
</script> 

使用此技巧,我们无需在应用中的多个位置填充重复属性的模板,同时仍然可以使用受欢迎的模板标记。

总结

使用本文中提到的示例,可以简化将多个属性传递给组件的操作。这对于具有很多属性的表示性和第三方组件特别有用。

注意,这里使用的示例仅仅演示。如果想制作更加灵活可用的,可以根据具体情况使用更好的方法,例如创建自己的包装器组件。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK